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 in Section 3.1, 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:
To use a style several times on a page, you must use classes. For example, when you have more than one photo on your page, use a class selector to apply stylingâlike a borderâto each of them.
Use IDs to identify sections that occur only once per page. CSS-based layouts often rely on ID selectors to identify the unique parts of a Web page, like a sidebar or footer. Part 3 shows you how to use this technique.
Consider using an ID selector to sidestep style conflicts, since Web browsers give ID selectors priority over class selectors. For example, when a browser encounters two styles that apply to the same tag but specify different background colorsâthe ID's background color wins. (See Section 5.4.3 for more on this topic.)
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. ...
Get CSS: The Missing Manual now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.