Digital humanities


Maintained by: David J. Birnbaum (djbpitt@gmail.com) [Creative Commons BY-NC-SA 3.0 Unported License] Last modified: 2012-10-10T15:59:13+0000


Using and @class to style your HTML

How to use @class

You can style in-line elements with such basic HTML tags as <em> for emphasis, <strong> for strong emphasis, etc., but what if you want to assign style that isn’t supported by the basic HTML tags? For example, what if you need to make your text red?

The HTML @class attribute is a very useful way to subcategorize HTML elements. For example, suppose you have two paragraph-like elements in your input XML, one for good examples of something (perhaps called <good_example>) and one for bad examples (perhaps called <bad_example>). You’d like to transform both into HTML <p> elements, but you want the good example to be green and the bad example to be red. In XML you gave them different names, so you could style them with different CSS rules, but HTML has predefined tags and is thus more restrictive; if you want them to look and behave like paragraphs, the natural way to do that is to make both <p> elements. Fortunately, you can still style these two paragraphs differently by giving them different values for the @class attribute. For example, if you output the good example as <p class="good">, you can specify in your CSS that all <p> elements whose @class attribute has the value of good should be colored green.

The syntax for specifying the value of the @class attribute in CSS is to concatenate, in order and with no intervening spaces, the name of the element, a dot, and the name of the class. For example:

p.good {color: green;}

says style all <p> elements with an attribute @class whose value is good by coloring the text green.

How to use <span>

Assigning a @class attribute value to an element like <p> to control its styling is natural because the element <p> occurs naturally in the structure of the output HTML. That is, it’s easy to style a paragraph because you can attach the @class attribute to the opening <p> tag. But what if you want to tag just a few words the middle of a sentence, which had a specific element structure in the original XML, but where there isn’t a corresponding HTML element to which you could transform it? That is, what if there’s no place to attach the @class attribute in the HTML output?

<span> is an all-purpose in-line element. It has no special meaning and no default rendering properties. The point of <span> is that it serves as a place to hang a @class attribute, enabling you to style arbitrary text. If, for example, your XML says something like:

<paragraph>On the wall there was a sign that said <warning>beware</warning></paragraph>

You could transform that into:

<p>On the wall there was a sign that said <span class="warning">beware</span></p>

and then include in your CSS:

span.warning { color: yellow; }

This would cause the word beware to appear in yellow.