CSS – Using Context-Based CSS Class Names

csshtml

This morning I found a note on my desk with some tips from a higher up developer who had been looking over some HTML/CSS I had put together.

One of his suggestions was for me to "stay away from context-based class and ID names like 'left' or 'right.' Never use colors as names. Stick to semantic names based on the content."

Is this valid advice? Why?

Best Answer

Yes. Definitely valid advice. CSS classes, for the most part, should not be tied directly to what they look like. Tie them, instead, to what they mean.

If you're using .blue to provide emphasis, and your site design changes so that you no longer want your emphasis to be blue, then you have a disconnect between the display of the element, and the class name.

If, instead, you used .emphasize, you could change the color in the CSS, and the HTML attribute would still be meaningful. You get the change without having to touch the HTML (or, in this case, you could style the em tag, and get even better semantics in the HTML).

In addition, it makes your CSS more readable. When you're changing .blue, it's not obvious what elements on your page you're changing. But if you're changing .emphasize or .pull-quote, you can immediately tell.

There are instances when non-semantic class names are unavoidable, but this is mostly when creating generic layout. Things like column or column-left or half or third are necessary in grid-based layouts.

So, my opinion is that layout doesn't need to be semantic, and usually won't be. But content should definitely be semantic. Ask yourself what your content is, and make the class name represent that, so it can be used in a meaningful way.

Related Topic