The CSS Anthology298
How do I decide when to use a class and
when to use an ID?
At first glance, classes and IDs seem to be used in much the same way: you can assign
CSS properties to both classes and IDs, and apply them to change the way (X)HTML
elements look. But, in which circumstances are classes best applied? And what
about IDs?
Solution
The most important rule, where classes and IDs are concerned, is that an ID must
be only used once in a document, as it uniquely identifies the element to which it
is applied. Once you have assigned an ID to an element, you cannot use that ID
again within that document.
Classes, on the other hand, may be used as many times as you like within the same
document. Therefore, if you have on a page a feature that you wish to repeat, a class
is the ideal choice.
You can apply both a class and an ID to any given element. For example, you might
apply a class to all text input fields on a page; if you want to be able to address those
fields using JavaScript, each field will need a separate ID, too. However, no styles
need be assigned to that ID.
I tend to use IDs for the main, structural, positioned elements of the page, so I often
end up with IDs such as header, content, nav, and footer. Heres an example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<title>Absolute positioning</title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="position2.css" />
</head>
<body>
<div id="header">
</div>

Get The CSS Anthology, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.