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.
- Keep
class
names meaningful. The value of the
class
attribute should provide a semantic description of adiv
orspan
’s content. Choosing names based on the intended presentation of the element—for example,class="indented"
orclass="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 asbluetext
are rendered in green.- Don’t go
class
-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 everyh1
element in a sidebar asclass="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.