An id selector matches the one element in the document whose id attribute equals the given name — because id values are meant to be unique per page, id selectors are inherently meant for one-off, page-specific targeting rather than reusable styling, and they carry considerably higher specificity than a class selector, which makes them noticeably harder to override later from elsewhere in a stylesheet. IDs also serve non-styling purposes, like being the target of an in-page anchor link (#section) or a target for JavaScript's getElementById(), which is one reason many style guides recommend reserving id attributes for those functional purposes and using classes for styling instead.
1Understanding ID Selectors
An id selector matches the one element in the document whose id attribute equals the given name — because id values are meant to be unique per page, id selectors are inherently meant for one-off, page-specific targeting rather than reusable styling, and they carry considerably higher specificity than a class selector, which makes them noticeably harder to override later from elsewhere in a stylesheet. IDs also serve non-styling purposes, like being the target of an in-page anchor link (#section) or a target for JavaScript's getElementById(), which is one reason many style guides recommend reserving id attributes for those functional purposes and using classes for styling instead.
Prefer classes over ID selectors for styling in most cases — an ID selector's high specificity makes it considerably harder to override later, and since an id is meant to be unique, it structurally can't be reused across multiple elements the way a class can.
#main-header {
background: navy;
color: white;
}2Practical Example
Here is a real-world application of ID Selectors showing how it is used in production CSS code.
#main-header { color: white; }
.header { color: black; }
<header id="main-header" class="header">Title</header>3Best Practices
Follow these guidelines when working with ID Selectors:
1. Reserve ID selectors mainly for genuinely unique, page-specific elements, or avoid using them for styling altogether in favor of classes
2. Remember an id's high specificity makes it hard to override later — a single ID selector can require an equally- or more-specific selector, or !important, to override
3. Use id attributes for their non-styling purposes, like anchor-link targets and JavaScript's getElementById(), even in codebases that otherwise avoid ID selectors for styling
Tip: Prefer classes over ID selectors for styling in most cases — an ID selector's high specificity makes it considerably harder to override later, and since an id is meant to be unique, it structurally can't be reused across multiple elements the way a class can.
#main-header {
background: navy;
color: white;
}