Giving Markup Some Class

One of the great things about CSS is the ability to give elements a class or id. The trouble is, like many other elements of XHTML/CSS, they can be abused. I know when I first began using CSS, I would give just about anything a class just because I could. I would then style elements based on their class, completely disregarding semantics. What resulted was cluttered markup filled with far too many class declarations, and a stylesheet that could use a trim.

<h1 class="main">Lorem Ipsum</h1>
<h2 class="level2">Fusce tellus</h2>
<p class="standout">Nam hendrerit. Vivamus mollis ipsum ac nisl. Fusce adipiscing. Nunc nec felis at neque vestibulum bibendum. Nulla commodo sollicitudin erat. Praesent feugiat.</p>
<h2 class="level2">Vestibulum at velit</h2>
<p class="regular">Vivamus mattis nunc quis metus. Nunc lobortis. Vestibulum sed tellus. Duis auctor.</p>

Coming Up With a Solution

While completely valid, markup like that degrades the stability of your code. When every element is given a class, you as the developer will need to continually remember to assign each and every element that class when you want the associated style applied.

A Recommendation

Instead, I recommend taking a step back and looking at the parent elements. Chances are there is a container element such as a div that definately deserves its own class and has one. You can use this to your advantage and have the container element act as a support for your style. Use the parent element to style the children.

div.content h1 { font-size:2.2em; }
div.content h2 { font-size:1.7em; }
div.content p { margin-bottom:1em; }
div.content p em { background-color:#efefef; }

Using CSS such as that would allow for the following markup:

<div class="content">
<h1>Lorem Ipsum</h1>
<h2>Fusce tellus</h2>
<p><em>Nam hendrerit. Vivamus mollis ipsum ac nisl. Fusce adipiscing. Nunc nec felis at neque vestibulum bibendum. Nulla commodo sollicitudin erat. Praesent feugiat.</em></p>
<h2>Vestibulum at velit</h2>
<p>Vivamus mattis nunc quis metus. Nunc lobortis. Vestibulum sed tellus. Duis auctor.</p>
</div>

Now, instead of markup cluttered with classes and a stylesheet with excessive code, we have a more streamlined version which is easier to follow and also easier to maintain.

In Closing

It is those circumstances when the style you wish to apply to an element is unique in nature when a specific class or id should be used. That way it will only make an effective appearance in the markup and in the stylesheet.