CSS ID Selector (#id) - When to Use and When to Avoid

Understand the CSS ID selector, its high specificity, and why modern CSS best practices often recommend class selectors instead. Learn the role of #id in specificity conflicts.

Basic Selectors

Detailed Explanation

The CSS ID Selector

The ID selector targets a single element with a matching id attribute. IDs must be unique within a document, so the ID selector always matches at most one element.

Syntax

#header {
  background: #333;
  color: white;
}

Specificity

An ID selector has specificity (1, 0, 0), which is significantly higher than class selectors. A single ID selector overrides any number of classes:

/* Specificity: (1, 0, 0) — wins */
#nav { color: red; }

/* Specificity: (0, 3, 0) — loses to #nav */
.main .sidebar .nav { color: blue; }

This high specificity is why many CSS methodologies discourage using ID selectors for styling.

IDs vs Classes for Styling

Feature ID (#id) Class (.class)
Uniqueness Must be unique per page Can be reused
Specificity (1, 0, 0) (0, 1, 0)
JavaScript getElementById() querySelectorAll()
Reusability Not reusable Fully reusable

When IDs Are Appropriate

  • Fragment identifiers — anchor links (#section-1)
  • JavaScript hooksgetElementById() is the fastest DOM query
  • ARIA relationshipsaria-labelledby, aria-describedby
  • Form labels<label for="email">

Overriding ID Specificity

If you need to override an ID-based style, you have several options:

/* Match specificity with another ID */
#content #nav { color: blue; }

/* Use !important (not recommended) */
.nav { color: blue !important; }

/* Use :where() to zero out specificity */
:where(#nav) { color: blue; }  /* specificity: (0,0,0) */

Use Case

ID selectors are essential for understanding CSS specificity and debugging cascade conflicts. While modern best practices favor class selectors for styling, IDs remain important for JavaScript hooks, ARIA accessibility attributes, and URL fragment navigation. Knowing when to use each is a key skill for front-end developers.

Try It — CSS Selector Reference

Open full tool