classes & IDs

You can also target specific areas of your document by adding IDs and class attributes to the tags in your XHTML markup. IDs and classes give you a second approach to styling your document.

Here is a piece of markup that illustrates how you might use a class:

<h1 class="specialtext">This is a heading with the <span>same class</span> as the second paragraph</h1>

<p>This tag has no class.</p>

<p class="specialtext"> When a tag has a class attribute, we can target it <span>regardless</span> of its position in the hierarchy.</p>

p.{font-family: Helvetica, sans-serif;}

.specialtext {font-weight:bold;}

.specialtext span {font-style:italic;}

This is a heading with the same class as the second paragraph

This tag has no class.

When a tag has a class attribute, we can target it regardless of its position in the hierarchy.

.specialtext span {font-style:italic;}

The words "same class" in the headline is italicized, by deleting the p from the start of the selector, you remove the requirement for the class to be attached to any specific tag. The downside is that other tags that you don't intend to style might also be affected because this modified rule is less specific.

 

IDs

IDs are written in similar way to classes, except you use a # (hash symbol) to indicate them in your CSS instead of the class's.(period)

If a paragraph is marked up with an ID, like this:

<p id="specialtext">This is the special text</p>

then the corresponding contextual selector looks like this:

p#specialtext {some CSS rules here}

Other than this, IDs work in the same way as classes. ID is more powerful than a class. According to the rules of XHTML only a single instance of a particular ID can be in a page, but class can appear many times. IDs are unique piece of your page's markup, such as the main navigation menu to which you want to target a special set of CSS rules.