Classes in Action

This section covers some potential uses of the class attribute, as well as reasons to avoid classes in certain cases.

Using Classes to Distinguish Off-Site/External Links

One of my favorite uses of class is to mark links to external pages, e.g.

<a class="extlink" href="http://www.cnn.com/"> CNN.com</a>

In the CSS, we might choose to make external links to display as red text, and internal links to display as blue text (which we might not make a class for, but rather just go with <a href="/link/in/mysite.php">).

Remember that all external links must be prefaced with http://.

Using Classes for First Paragraphs

Sometimes, we like to visually distinguish a first paragraph after a header, perhaps by making the line-spacing bigger, etc. Although there is a way to achieve this in CSS (using the child combinator, which we'll examine in the CSS section) without a special <p class="firstparagraph"> class, it's not supported in all browsers. And there's nothing structurally wrong with identifying a first paragraph, even if our goal is to distinguish it visually later on.

Creating a noshow Class

Once you begin to create more advanced pages using things like image replacement, it can be helpful to have a class that deliberately hides things from graphical browsers (though, happily enough, not from screen readers) using CSS and the display: none property. We could even use noshow with a <span> tag in the markup of the external links example from above (since screen reader and blind users won't get the color scheme:

<a class="extlink" href="http://www.cnn.com"> <span class="noshow">External link to</span> CNN.com</a>

To graphical browsers this would appear as: External link to CNN.com.