Presentationally descriptive class attributes

04 Jun 2013

… are bad

Class and id attributes should be used to describe the meaning of different objects, not how they are presented. Presentation should be entirely described in the css.

Inline styles are bad

These are inline style in disguise.

Here’s how we can use Sass1 to rid ourselves of this plague.


Warning notes:

Rise of the presentationally descriptive class attributes

The advent of bootstrap (itself written in Less2) has led to some developers to use presentationally descriptive class attributes.

TODO give example:

We can use Sass’ @extend3 (this can also be done using Less4) to keep the main code have purely descriptive classes.

TODO come up with analolgy to object oriented inherit…

Remove inline styles:

<span style="color: red">alert</span>

to

<style>
  .alert {color: red;}
</style>
<span class="alert">alert</span>

Remove inline classes:

Note: this is rather an simplified example, and surely not a real-life one…

<style>
  .red {color: red;}
</style>

<span class="red">alert</span>

to

<style> // Note: this is in your sass file
  .red {color: red;}
  .alert {@extend .red;}
</style>

<span class="alert">alert</span>

This reads: extend .alert to give it the properties of .red.

Note: this compiles (in CSS) to:

<style>
  .red, .alert {color: red;}
</style>

<span class="alert">alert</span>

In this way, if you want to change all of the “alerts” from .red to .blue, then you only need change one line in the sass.

Extend multiple classes

You can also @extend multiple classes:

<style>
  .red {color: red;}
  .bold {font-weight: bold;}
  .alert {@extend .red; @extend .bold;}
</style>

<span class="alert">alert</span>

which compiles to:

<style>
  .red, .alert {color: red;}
  .bold, .alert {font-weight: bold;}
</style>

<span class="alert">alert</span>

Warning notes

The order is critical

The order of these is critical, as with all css the things lower down have precendence (if they have the same score/specificity5 6).

Keeping those classes you which to @extend at the below those which they are extending from should help you to preserve some sanity.

Specifiers not extending?

TODO mention something about some specifiers not extending (e.g. :first?).

blog comments powered by Disqus