Avoid over-using CSS classes

Posted 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).

    <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>

This isn't even a particularly bad example; I've seen a lot worse. Here's the CSS:

.tab {
    /* 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>

And the alternative CSS looks like this:

.tabs li {
     /* styling here */

You can make this apply to all sorts of HTML/CSS and remove all sorts of unecessary class="foo" bits of code in your HTML.

Related posts: