Small but Significant Difference

ID tag

Looking for the lessons? Get started!

Classes and IDs, the similarities and differences.

The entire Web Design Principles section can be accessed through the menu below.

Unfortunately, not everyone’s browser will support the spiffy JavaScript menu behind that innocent-looking button. If your browser won’t display the menu, just click on the button and you’ll be taken to a separate page with the entire menu displayed in clear, non-JavaScript HTML.

IDs are unique and beautiful snowflakes. Classes are not. — Rob Glazebrook

css icon

We use classes and IDs to hang specific modifications from in our stylesheets.

What exactly does that mean?

In and of themselves, classes and IDs do nothing. It’s what we do with them that counts. We "hook" things to them.

Web designer and tutorial creator Chris Coyier writes:

These ID’s and Classes [are] the “hooks” we need to build into markup to get our hands on them. CSS obviously needs these so that we may build selectors and do our styling, but other web languages like Javascript depend on them too.

You don’t always use either a class and ID to style elements. You can simply hang your styling directly off of the element (or tag, as many call them):

p {
   font-size: 16px;
}

This can be a bit crude, and can sometimes have unforeseen consequences down the road, requiring you to add some finesse to your stylesheet at a later date. But you can do this, sometimes you should do it, and it is valid to do so.

The folks at CSS-Discuss note:

Classes are useful to apply similar declarations to a variety of elements. In design, you often want thematic style to be applied consistently. For example, you may wish for all external links to be red, while internal links are blue. Using the class attribute in this case makes sense. IDs are useful to uniquely identify a particular element. On the face of it, this may seem to be a narrow use, but if you consider that a Contextual Selector [see below] can be used to apply declarations to elements which are contained by a particularly ID’ed element, the usefulness is greater. For example, you may wish to have all menu links be green, while content links are red. Placing the menu inside an element which is ID’d as “menu” or “content” respectively allows you to make contextual styling based on the section of the page.

Wow, that was confusing. Accurate, but confusing (and when you get this concept figured out, you’ll reread this quote and agree with it completely).

Coyier explains it a bit more lucidly:

We need ways to describe content in an HTML/XHTML document. The basic elements like <h1>, <p> and <ul> will often do the job, but our basic set of tags doesn’t cover every possible type of page element or layout choice. For this we need ID’s and Classes. For example <ul id="nav">, this will give us the chance to target this unordered list specifically, so that we may manipulate it uniquely to other unordered lists on our page. Or we might have a section on our page that has no relevant tag to signify it, for example a footer, where we might do something like this: <div id="footer">. Or perhaps we have boxes in our sidebar for keeping content over there separated in some way: <div class="sidebar-box">.

Did that help you or confuse you? Maybe a little of both?

That’s partly because Chris is talking about using classes and IDs for layout purposes, something you may not have gotten to yet.

More about layouts.

In the stylesheet, classes and IDs can either stand alone or go with an HTML element:

either

.bigfont {
   font-size: 4em;
}

or

p.bigfont {
   font-size: 4em;
}

Notice that the class is designated by the period in front of the class name: .bigfont. Just the word "bigfont" by itself would mean nothing in your stylesheet.

Both of these examples make a pretty huge font when applied to a specific chunk of code. The first class, bigfont, can be applied to anything: an unordered list, a blockquote, a heading, whatever. It’s what the code warriors call "an implied universal selector," applying to anything you like. The second, bigfont p, will only work if applied to a paragraph (<p>).

Here’s how either of them would work in your HTML page:

<p class="bigfont">text to be enlarged</p>

Only the text in the paragraph classed bigfont would be enlarged.

You can even use multiple classes in a single CSS element. Here’s an example suggested by Olsson and O’Brien, and modified by me:

div.foo.bar {
   font-size: 4em;
}

div.foo.bar[title^="Help"] {
   font-size: 4em;
	color: #ff08ff;
}

In the first selector, the div labeled with two classes, .foo and .bar, would only effect changes on an HTML div element with both classes incorporated into it:

<div class="foo bar">Matches 1st example</div>

In the second selector, the div labeled with two classes, .foo and .bar, and incorporating the title, Help, would only effect changes on an HTML div element with both classes incorporated into it:

<div class="foo bar" title="Help">Matches 2nd example</div>

Note: Internet Explorer has some bugaboos with classes. In IE6, the class selector doesn’t work if the class name starts with a hyphen (-) or an underscore (_). IE6 and below (IE5.5, for example, which few people bother with designing for, but IE6 is still out there in all its persnickety glory), if you use multiple class selectors (as in our example above), it will only pay attention to the last selector, and will ignore the others. Grr.

The Difference between Classes and IDs

An ID (short for identifier), works exactly like a class. Everything written above also applies to IDs.

So what’s the difference? Actually, some fairly big ones.

An ID is identified by a # instead of a ., like so:

#bigfont {
   font-size: 4em;
}

An ID can only be used once per HTML page, where a class can be used over and over again. There’s a reason for that: the # mark is used for internal links, like so:

http://www.example.com#comments

The browser goes directly to the element ID’d as “comments”.

Let’s say that again, with feeling:

An ID can only be used once per HTML page, where a class can be used over and over again.

If you do repeat an ID in a page, some browsers will be forgiving enough to display it the way you meant it to be seen, but some won’t. And it will not pass a validation check.

More about validating your pages.

Coyier gives us a terrific analogy about the difference between classes and IDs:

Maybe a good analogy here is bar codes and serial numbers. Take an iPod in a store. On the packaging will be a bar code. This tells the store what the product is, so when it is scanned, the system knows exactly what the product is and what it costs. It might even be able to know what color it is or where it was kept in the store. All iPod of this same type have the exact same bar code on them.

The iPod will also have a serial number on it which is absolutely unique to any other iPod (or any other device) in the world. The serial number doesn’t know the price. It could, but for the store this wouldn’t be a very efficient way to store and use that data. Much easier to use the barcode, so that for example, if the price changed, you could just change the price for that bar code and not every individual serial number in your system.

This is much like ID’s and Classes. Information that is reuseable should be kept in a class and information that is totally unique should be kept in an ID.

You can specify a particular element to be affected with the ID selector:

ul#navigation {
   font-size: 2em;
}

but make sure no whitespace is between the type selector and the ID selector. In other words, this:

ul #navigation { WILL NOT WORK!
   font-size: 2em;
}

will not work!

Note: Internet Explorer 6 will ignore an ID selector unless it’s the last one in the selector; if you put a class after it in a multiple selector, IE6 will not recognize it. Grr again.

Limiting Classes to Specific Elements

One thing you can do with a class that you can’t do with an ID is to give specific elements with that class particular styling, while not putting that styling on other instances of that class.

Say what? Here’s an example.

Say you’ve created a class called “critical”, used for the most important parts of your text content. You want to style it in a classy serif font, boldface it, increase its size a bit, and expand the letter spacing to set it off just that little bit more:

.critical {
   font-weight: bold;
   font-family: "Palatino Linotype", "Book Antiqua", "Century Schoolbook", Georgia, serif;
   letter-spacing: 0.05em;
}

But, you decide that text inside a blockquote should be italicized instead of made bold. Easy enough:

blockquote.critical {
   font-weight: normal;
   font-style: italic;
}

Note there is no space between "blockquote" and ".critical."

Now, this text:

<blockquote class="critical">
   <p>Important text.</p>
</blockquote>

will appear in the proper font, with the proper letter-spacing, but italicized instead of in boldface.

Ian Lloyd explains it better than I can:

By prefixing our normal class selector with an element name, we’re telling the browser to apply the following declarations to that element-and-class combination only. It’s as simple as element.class, but make sure you don’t leave any spaces!

And Rob Glazebrook observes:

[T]he more specific you are, the less danger you’re in of accidentally styling things you didn’t mean to.

Using Classes and IDs Semantically

Coyier reminds us about using classes and ID semantically. Instead of paraphrasing, let’s just quote him:

Also avoid this:

<div id="right-col">

ID is appropriately used here as the page will likely only have a single right column, but the name is inappropriate. Try and describe the context of the element, not where it is or what it looks like. An ID here of "sidebar" would be more appropriate.

This is a mistake I commonly make, so don’t repeat my blunders.

Web designer Meitar Moscovitz emphasizes the importance of using semantically descriptive names for your classes and IDs. He writes:

[W]hen crafted thoughtfully, ID and class attributes can … improve our code’s organization, readability, and can directly improve many aspects of developer-to-developer communication, which can be particularly important on large teams."

When naming his classes and IDs, Moscovitz asks himself the following questions to help guide him towards a useful name:

  • What function does the element serve? (Why’s it there? What’s its purpose?)
  • Are there other elements that serve similar functions? (How similar? What are the differences between them?)
  • Are there other websites that use elements for the same purposes? (What are those named?)

He uses the typical example of a site navigation scheme.

Answering the first question: since the element is for site navigation, the name should reference the concept of “navigation.”

Answering the second question: Since it’s likely that your site will include more than one navigation element of some sort, it’s useful to call this particular element something besides just “navigation.” Moskowitz posits the following possibilities: “mainnavigation”, “sitenavigation”, “navigationbar”, “globalnavigation”, or something similar, depending on this element’s function. (The other names might be useful for other navigational elements.)

Let’s say we choose the name “sitenavigation” for the ID or class.

Answering the third question: since “nav” is a common name, and used by many other sites, there’s every reason to go ahead and use it in your code. So we go from “sitenavigation“ to the shorter, more easily typed “sitenav”. And we get:

<ul id="sitenav">
   <li><a href="index.html">Home</a></li>
   <li><a href="about.html">About</a></li>
</ul>