The CSS #id selector
The CSS ID selector targets the single element with a given id, written with a hash — #header { … } styles the element with id="header". An ID should be unique on the page. Its specificity is very high and hard to override, so for styling most developers prefer classes.
Overview
The ID selector matches one element — the one with a matching id attribute — using a hash: #main { … }. Because an id must be unique within a page, an ID selector is for that single, specific element, not a group.
It works, but it comes with a catch: very high specificity (1,0,0). An ID selector beats any number of class selectors, which makes its styles stubborn to override and tends to start specificity wars that end in !important. For that reason the common guidance is to avoid IDs for styling and lean on classes instead, which stay flexible.
IDs are still genuinely useful — just for other jobs. They are the target of in-page anchor links (href="#section"), the hook that label for="" and ARIA attributes like aria-labelledby point at, and a fast handle for JavaScript. Use IDs for those roles, and style with classes.
Syntax
/* matches the single id="header" */
#header {
position: sticky;
top: 0;
}
Example
<style>
#hero {
background: #1c7ce9;
color: #fff;
padding: 22px;
border-radius: 10px;
text-align: center;
font: 700 18px system-ui, sans-serif;
}
</style>
<div id="hero">Styled with #hero (one unique element)</div>
Best practices
- Prefer classes for styling; reserve IDs for anchors, form labels, ARIA references and JavaScript hooks.
- Keep every
idunique on the page — duplicate IDs are invalid and break label and anchor behavior. - Be aware an ID selector's high specificity makes its styles hard to override; that is the main reason to avoid it in CSS.
- If you must override an ID-based style, you generally need another ID or
!important— a sign to refactor toward classes.
Frequently asked questions
How do I select an ID in CSS?
#header { … } styles the element with id="header".Should I use IDs or classes for styling?
Can I use the same ID on more than one element?
id must be unique per page. Duplicates are invalid and break anchor links, label for and ARIA references.