IDs and Classes

Sometimes, you need finer control over telling the browser what part of the page you'd like to style. Maybe you'd like to link to certain sections of a page in particular, perhaps for a table of contents. These are where IDs and classes come into play.

IDs

An element ID is a parameter that gives a generic element a more specific name. The name can be anything you want, and you can then reference this in a link or in a stylesheet. The only rule with IDs is that they cannot be reused. If you have two elements on a page with the same ID, it won't be valid HTML, and a validator will choke on it. It also has the ability to trip up less sane browsers.

To give an element an ID, use the id parameter:

<h2 id="sandwiches">

Then, to reference it, use the ID name prefaced with a pound sign, or #sandwiches.

The effect of this, won't be immediately apparent, but this can then be used in a stylesheet to style only that <h2>:

#sandwiches {
		font-family:"Curlz MT", Fantasy;
		color: #E00057; }

Or, to link to that header:

<a href="#sandwiches">Our delicious sandwich menu</a>

The table of contents to the left uses IDs to link to parts of the page.

Classes

What if you want to style a whole group of elements? This is where classes come into play. Classes can't be linked to, but they can be reused to group a set of generic elements into a more specific set of elements. To give an element a class, use the class parameter:

<a class="navlink">

And to reference it, preface the class name with a period, such as .navlink.

.navlink {
		padding: 5px;
		font-size: 14pt; }

If a variety of elements share classes, you can use a.navlink to specify only <a> elements with the .navlink class, or you can specify only the class to select all elements with that class. As my stylesheet has <a> .navlink elements and <span> .navlink elements, and I'd like to select all of them, I use .navlink.

Or, more simply, .navlink {...} will match <a class="navlink">, <span class="navlink">, or <h2 class="navlink">, while a.navlink {...} will only match <a class="navlink">.

Mixing classes and IDs

An element can have both an ID and a class, and it can have multiple IDs and classes. An <span id="home" class="intro yellow"> element has an ID of #home and is part of two classes, .intro and .yellow.

Summary:

  1. If you need to reference a specific element or set of elements, you can use IDs or classes.
  2. IDs are defined using the id parameter on an element. Reusing IDs is not allowed, but you can link to any part of a page using an ID.
  3. Classes are defined using the class parameter on an element. You can reuse classes as much as you want, but you can't link to them.