Reusable CSS classes

Reusability is the key to keep our code organized and easy to maintain. When dealing with CSS class names, two are the points to keep in mind:

  1. semantics of class names
  2. cascade and specificity

Semantics of class names

You should avoid presentational class names, such as bold or red. Instead, use descriptive names that specify what is the purpose of a particular class, such as evident or highlight.

Cascade and specificity

Classes can be combined together to form cumulative styles. For example, suppose that you have the following class:

.highlight {
  background-color: #ffc;
  font-weight: bold;

Then you can specify another class in your stylesheet:

.note {
  background-image: url("note.png");
  background-repeat: no-repeat;
  height: 100%;  /* IE6/7 hasLayout */
  padding: 1.2em;

Finally, you can combine them in your markup:

<div class="note highlight">..</div>

The final result is an element whose styles are the sum of the rules specified in the two classes. Of course you can use a single class or both classes on different elements, because we didn't specify an element type on our class selectors. Only remember to avoid clashing style rules, because if you do so, then the rules for specificity will be applied.

Leave a Reply

Note: Only a member of this blog may post a comment.