How do ID selectors work in CSS, and how do they differ from classes?
An id selector starts with a hash (#navigation) and targets the single element whose id attribute matches — an id is meant to be unique on the page.
Where a class is a reusable label, an id is a unique name for one specific element:
#eins {
color: #884422;
}
<p id="eins">Absatz</p>
An id is meant to appear once per page. The same id value will also be used later by JavaScript to grab that exact element, which is another reason to keep ids unique.
How id and class compare:
| Aspect | id (#name) |
class (.name) |
|---|---|---|
| How often | Once per page | As many times as you like |
| Specificity | (1,0,0) — very high | (0,1,0) — moderate |
| Best for | One unique element | Reusable styles |
The gotcha is that high specificity: because an id beats any number of classes, a style set via #footer is hard to override later without escalating further. For that reason the common guidance is to prefer classes for styling and keep ids mainly for unique hooks (anchors, JavaScript targets).