Simple classes enable you to target any element in the document, regardless of its position in the hierarchy.
Let's begin the discussion with a very simple example. The CSS rules and markup are followed by an example of how that code renders. Below that I will discuss the effect of the CSS.
Example Style sheet
p { font-family: Verdana, sans-serif; }
.specialtext { font-weight: bold; }
In the above style sheet, we are specifying a rule for the "specialtext" class.
- Class names begin with a period (.) in the style sheet.
- Class names are case-dependent and must conform to
XHTML
naming conventions
.
Example Markup
<h3 class="specialtext">This is a heading with the same
class as the last paragraph.</h3>
<p>This first paragraph has no class.</p>
<p class="specialtext">
When a tag is identified with a class, we can target
it <span>regardless</span> of its position
in the hierarchy.
</p>
In the markup above, we are attaching the specialtext class to the H3 text and the last paragraph. Note that the first paragraph does not have a class attached to it.
class
attribute, and furnish the
name of the class.
- Note that the period is omitted in the markup!
- The class name used in the markup must match exactly (including case) with the class name specified in the style sheet.
The Rendered Example
This is a heading with the same class as the last paragraph.
This paragraph has no class.
When a tag is identified with a class, we can target it regardless of its position in the hierarchy.
Both paragraphs display in the Verdana font (if available) while the H3 heading displays in the browser's default font and size.
Unlike an ID which can only be assigned to one unique element per document, classes can be applied to multiple elements in a document.
Notice that we have attached the specialtext class to multiple elements in the document. The heading and bottom paragraph are each bold because they share the specialtext class. In this example, we have attached the specialtext class to block-level elements, but you can also attach the specialtext class to inline elements if you desire.
The SPAN tag is un-styled at this point so it has no effect.
Now, let's continue our discussion of class selectors with the topic of specifying multiple classes.