css subclass mess

This entry was posted on Monday, March 30th, 2009

Recently I was given the task of integrating a new dynamic css/xhtml template into an existing template. Nothing too exciting but the markup made extensive use of css subclasses. By extensive I mean some elements had 3 classes plus an ID! The problem with so many subclasses was that it took me far too much time figuring out which ones I needed to edit in order to make a change. Ensuring cross browser compatibility was also a chore because I had multiple subclasses to deal with. So for those of you who rely on subclasses I urge you to read on.

A brief intro to subclasses

CSS allows for an unlimited number of space-delimited classes:

<div class="class1 class2 ect">
     <p>...content...</p>
</div>

The order of the classes doesn’t matter but its always a good idea to first list the base class followed by the subclass. It’s much easier to read that way.

The problem

You are inviting trouble when you rely on subclasses (especially for structure) throughout your markup. Consider the following extreme case which I recently encountered on a project:

<div class="line breather gradient-top">
     <p>...content...</p>
</div>

The CSS:

div.line {
  ...rules...
}
div.breather {
  ...rules...
}
div.gradient-top {
  ...rules...
}

That’s 3 sets of different rules in the stylesheet for one element! What a mess! (There are more serious issues like not separating content and presentation, but that is beyond the scope of this post). There is another method using dot notation that could have been used to chain the subclasses- http://www.w3.org/TR/CSS21/selector.html#class-html. Either way is more complicated than need be.

The solution

A better approach would be to use a single class selector that is meaningful. Let’s assume the content to be styled is the main content. Naming the class selector “mainContent” gives the markup meaning making it easier to read and edit:

<div class="mainContent">
     <p>...content...</p>
</div>

The CSS for the previous element is now located in a single set:

div.mainContent { 
     ...rules...
}

Of course, there will be situations where using subclasses makes sense. Just be aware of the consequences of relying on them.

To briefly summarize the benefits of using a single meaningful selector:

  • Your markup and stylesheet will be cleaner, easier to read and understand
  • Maintenance will be easier for yourself and especially others
  • Saves time/money

Happy coding.

Comments are closed.