CSS Reference ยท Selectors
The #id selector
Reference for the CSS ID selector: match the one element with a given id, its high specificity, how it differs from classes, and when to avoid it.
The ID selector starts with a hash sign and matches the element whose id attribute equals the given name. An id must be unique in a document, so the selector is meant to find exactly one element.
IDs carry high specificity (1,0,0), which beats any number of classes. That makes them powerful as link targets and script hooks, and awkward as styling hooks.
#site-header { border-bottom: 1px solid #ced4da; }
Try it
Even though the second box matches .box.highlight.big (0,3,0), #special (1,0,0) is more specific, so its background is blue.
Syntax and arguments
#name { } /* element with id="name" */ div#name { } /* only if it is a <div> */ [id="name"] { } /* attribute form, lower specificity */ #a #b { } /* #b inside #a */
| Part | Description |
|---|---|
#name |
Matches an element whose id equals name. Case-sensitive in standards mode. |
| Specificity | 1,0,0 per ID. |
| Valid names | A valid identifier; characters like : or . and a leading digit must be escaped (#\31 23). In HTML, an id itself only needs to be non-empty and free of spaces. |
Usage notes
- Unique by rule. If several elements share an
id, the HTML is invalid. Browsers will still style all of them with#name, butgetElementByIdand fragment links only see the first. - Hard to override. Because one ID beats any pile of classes, later changes often need another ID or
!important. Most style guides therefore use classes for styling and keep IDs for anchors, labels (for/id) and ARIA relationships. - Lowering specificity. Writing
[id="name"]has class-level specificity (0,1,0), which can help when you must select an element that already has an ID. - Fragments. An ID is also what
#sectionin a URL scrolls to, and what:targetmatches. - Duplicates in components. Reusable components should not hardcode IDs; the same component placed twice would duplicate them.
- JavaScript.
document.querySelector("#name")uses the same syntax.
Browser support
Supported in every browser.