CSS ID Selector (#id) — Targeting a Unique Element
Understand the CSS ID selector for targeting a single, unique element by its id attribute. Learn about specificity implications and when to use IDs vs classes.
Detailed Explanation
CSS ID Selector
The ID selector uses a hash (#) prefix to target an element by its unique id attribute. Since IDs must be unique within a document, this selector always matches at most one element.
Syntax
#header {
/* styles applied to the element with id="header" */
}
Specificity Impact
An ID selector has a specificity of (1, 0, 0), which is significantly higher than class selectors (0, 1, 0). This means an ID-based rule will override class-based rules regardless of their order in the stylesheet.
.nav { color: blue; } /* specificity: (0, 1, 0) */
#main-nav { color: red; } /* specificity: (1, 0, 0) — wins */
ID vs Class: When to Use Each
| Feature | ID | Class |
|---|---|---|
| Uniqueness | Must be unique per page | Can be reused |
| Specificity | High (1, 0, 0) | Medium (0, 1, 0) |
| JavaScript | getElementById() |
getElementsByClassName() |
| URL anchors | Yes (#section) |
No |
| Recommended for styling | Rarely | Yes |
Common Pitfalls
- Overuse of IDs makes styles hard to override without
!important - IDs create tight coupling between CSS and HTML structure
- Refactoring becomes difficult when IDs are scattered throughout stylesheets
- Modern CSS methodologies (BEM, SMACSS) discourage ID selectors for styling
Use Case
ID selectors are primarily used for JavaScript hooks (getElementById), URL fragment navigation (#section anchors), and accessibility landmarks (aria-labelledby). While they can be used for styling, most CSS methodologies recommend classes instead due to the high specificity of IDs. Form elements often use IDs for label association with the for attribute.