Working with Classes and IDs

There are two powerful attributes for adding additional structure to your XHTML pages: class and id. This page gives you some general tips about working with classes and ids.

class Versus id

A simple way to think about classes and ids is to think of a particular group of students, the freshman class at Whatsamatta U. All of the students make up that particular class, which is distinguished from the sophomore, junior, and senior classes. There may be 20 members of the freshman class, or 2000. In contrast, there can only be one student with an ID number of 123-45-6789. ID numbers are unique, describing one and only one individual, while classes describe groups.

The same idea is true in XHTML markup. We could have a class with the name "important," which might enhance a document on instructions. Later, in the CSS, we can set up some display instructions that make all text with the class "important" display as red.

We might also have a central navigation area, which we could assign the id to as "navigation" (this is usually done in conjunction with the <div> tag). There will be, in this page, only one part of the document with the id of "navbar".

Rules for Naming Classes and IDs

There are a few simple but crucial rules that must be followed when naming classes and IDs.

  • Classes and IDs must begin with a letter a-z. It's generally best practice to leave classes and IDs in lower-case letters (so you don't have to remember if you went with "NavBar," "Navbar", or "navbar"), but they absolutely cannot start with a number (e.g., "1stparagraph").
  • Classes and IDs must be enclosed in quotation marks in XHTML markup. Your markup should read something like <p class="important"> or <div id="pageheader">. Although you could get away with <p class=important> in HTML, XHTML requires quotes around all attribute values.
  • Name classes and IDs based on structural function, not visual presentation. For example, go with a class called "important" to mark important text, rather than "red"; "red" may make sense for your current design, but it might not if you change important text to be big, black and bold.
  • If you find yourself naming a class that matches the function of a structural tag, use the structural tag! This may seem like a no-brainer, but I've seen students do something like <p class="header">, when of course they should just use the <h1> tag.