ID Selectors: Specific Page Elements

CSS reserves the ID selector for identifying a unique part of a page, like a banner, navigation bar, or the main content area. Just like a class selector, you create an ID by giving it a name in CSS, and then you apply it by adding the ID to your page's HTML code. So what's the difference? As explained in the box on Styling Groups of Tags, ID selectors have some specific uses in JavaScript-based or very lengthy web pages. Otherwise, compelling reasons to use IDs over classes are few.

When deciding whether to use a class or an ID, follow these rules of thumb:

Note

Although you should apply only a single ID to a single HTML tag, a browser won't blow up or set off alarm bells if you apply the same ID to two or more tags on the same page. In fact, most browsers will apply the CSS from an ID style correctly in this case. However, your HTML won't validate (see The Importance of the Doctype), and your web designer friends may stop talking to you.

Should you decide to use an ID selector, creating one is easy. Just as a period indicates the name of a class selector, a pound or hash symbol identifies an ID style. Otherwise, follow the exact same naming rules used for classes (Class Selectors: Pinpoint Control). This example provides a background color and a width and height for the element:

#banner {
  background: #CC0000;
  height: 300px;
  width: 720px;
}

Applying IDs in HTML is similar to applying classes but uses a different attribute named, logically enough, id. For example, to indicate that the last paragraph of a page is that page's one and only copyright notice, you can create an ID style named #copyright and add it to that paragraph's tag:

<p id="copyright">

Note

As with class styles, you use the # symbol only when naming the style in the style sheet. You leave the # off when using the ID's name as part of an HTML tag: <div id="banner">.