Tips on using class

There is a heady exhilaration that comes with the ability to create your own custom elements using id and class. The class attribute in particular is prone to misuse. These tips should provide some basic guidance for keeping your markup clean.

Keepclassnames meaningful.

The value of the class attribute should provide a semantic description of a div or span’s content. Choosing names based on the intended presentation of the element—for example, class="indented" or class="bluetext"--does little toward giving the element meaning and reintroduces presentational information to the document. It is also short-sighted. Consider what happens when, in an inevitable future design change, all elements classified as bluetext are rendered in green.

Don’t goclass-crazy.

It’s easy to go overboard in assigning class names to elements. In many cases, other types of selectors, such as contextual or attribute selectors, may be used instead. For example, instead of labeling every h1 element in a sidebar as class="sideread", a contextual selector could be used, like this:

    div#sidebar h1 {font: Verdana 1.2em bold #444;}

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.