Avoid over-using CSS classes
Posted January 23rd, 2010 in HTML and CSS
A couple of weeks ago I checked out a new site that had just launched and decided I'd take a look at the source and see what they'd done behind the scenes. The overuse of CSS classes on that website was what prompted me to write this post. You don't need to make every sub-element have a class; give the parent the class instead and simplify your code and style sheets with child element styling.
Bad example
Here's an example of overuse of CSS classes. (Hint: those <li>s don't need a class each; the parent can have a class which you can style as .foo li instead).
<ul> <li class="tab"><a href="...">Home</a></li> <li class="tab"><a href="...">About Us</a></li> <li class="tab"><a href="...">Blah blah blah</a></li> <li class="tab"><a href="...">Something else</a></li> </ul>
This isn't even a particularly bad example; I've seen a lot worse. Here's the CSS:
.tab {
/* some lovely styling here */
}
Yes, there's nothing wrong with the CSS but I just don't like all those unecessary classes in the HTML.
How it should be
Well OK so that's not really all that bad (as I said above I've seen a lot worse and the CSS is perfectly acceptable), but this is what it should look like (I've moved the class from the li elements to the ul):
<ul class="tabs">
<li><a href="...">Home</a></li>
<li><a href="...">About Us</a></li>
<li><a href="...">Blah blah blah</a></li>
<li><a href="...">Something else</a></li>
</ul>
And the alternative CSS looks like this:
ul .tabs {
/* some lovely styling here */
}
Hooray! You can make this apply to all sorts of HTML/CSS and remove all sorts of unecessary class="iAmAWonderfullClass" bits of code in your HTML.
Comments below would be welcome but I haven't coded them into my CMS yet but they are coming soon - hooray! :)
Related posts:
- "Clearing" floats with overflow: auto (Saturday, January 9th 2010)
- Valid characters for the HTML ID attribute (Saturday, April 4th 2009)
- Multiple CSS classes for a single element (Saturday, March 21st 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

