Hypermile your CSS

Have you heard these rules for best practices in web design?

  1. Keep your HTML as lean as possible – stick with plain old semantic HTML (POSH)
  2. Put all your presentation rules in the CSS

Well, it’s possible to do #2 while failing at #1. That’s because of a condition known as classitis. Classitis is a condition in which your HTML is cluttered up with multiple classes when just one would do the trick. Classitis happens when the class attribute gets attached to the wrong element in your HTML.

An example of classitis

Look at this code. The purpose is to style the contents of a blockquote to look a particular way.

<blockquote>
<p class="pullout">Yakkity yak, don't look now but this is classitis.</p>
<p class="pullout">Yakkity yak, don't look now but this is classitis.</p>
<p class="pullout">Yakkity yak, don't look now but this is classitis.</p>
</blockquote>

Notice the class applied to each paragraph in the blockquote? That’s a bit of overkill that adds a class rule into your HTML in three places, when only one would be enough.

Hypermile that class

You can make the same thing happen more efficiently and with leaner HTML. Here’s how.

<blockquote class="pullout">
<p>Yakkity yak, this blockquote is lean and mean.</p>
<p>Yakkity yak,
this blockquote is lean and mean.</p>
<p>Yakkity yak,
this blockquote is lean and mean.</p>
</blockquote>

Apply the class to the parent or container element – in this case the <blockquote>. The results will be the same as if you had applied the class to every individual element within that container.

The same kind of thinking would apply if you were styling a list. Apply the class to the <ul> or <ol> element, not to each individual <li>. If you were styling text in a <div>, <article> or <section>, apply the class to the parent element rather than to child elements like paragraphs within a div or article.