Index by Christopher Schmitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Determining When to Use Class and ID Selectors

Problem

You want to determine the best use for class and ID selectors.

Solution

Use class selectors when you need to apply a style multiple times within a document, and ID selectors for one-time-only appearances within a document.

In the following stylesheet, #banner and #content are ID selectors and .title and .content are class selectors:

body {
 margin: 0;
 font-family: Verdana, Arial, Helvetica, sans-serif;
 font-size: .75em;
 padding: 0;
}
#banner {
 margin-top: 0;
 margin-bottom: 0;
 background-color: #900;
 border-bottom: solid 1px #000;
 padding: 5px 5px 5px 10px;
 line-height: 75%;
 color: #fff;
}
#sub_banner {
 background-color: #ccc;
 border-bottom: solid 1px #999;
 font-size: .8em;
 font-style: italic;
 padding: 3px 0 3px 10px;
}
#content {
 position: absolute;
 margin-left: 18%;
 width: 40%;
 top: 100px;
 padding: 5px;
}
#nav1 {
 position: absolute;
 width: 30%;
 left: 60%;
 top: 100px;
 padding: 5px;
}
#nav2 {
 position: absolute;
 padding: 5px 5px 5px 10px;
 top: 100px;
 width: 15%;
}
#footer {
 text-align: center;
 padding-top: 7em;
}
.warning {
 font-weight: bold;
 color: red;
}
.title {
 font-size: 120%;
}
.content {
 font-family: Verdana, Arial, sans-serif;
 margin-left: 20px;
 margin-right: 20px;
}
.footer {
 font-size: 75%;
}

Here are the ID and class selectors in the HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>CSS Cookbook</title> <link href="1-2.css" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required