CSS: Selectors, Properties & Specificity
What you will learn
How to select HTML elements and style them with properties, and the concept of specificity — which rule wins when multiple rules target the same element.
Basic rule structure
h1 {
color: blue;
font-size: 24px;
}
p {
color: gray;
line-height: 1.6;
}
Every CSS rule has a selector (what to target) and a declaration block with properties and values. Use property: value; syntax.
Selectors reference
| Selector | Targets | Specificity |
|---|---|---|
h1, p |
All elements of that type | 0,0,0,1 |
.classname |
Elements with that class | 0,0,1,0 |
#idname |
The element with that id | 0,1,0,0 |
div p |
p inside div (descendant) |
Sum of parts |
div > p |
Direct child p of div |
Sum of parts |
[type="text"] |
Elements with that attribute | 0,0,1,0 |
* |
All elements | 0,0,0,0 |
Specificity (how conflicts are resolved)
When two CSS rules target the same element, the one with higher specificity wins. Think of it as a score:
- Inline styles (
style="...") — highest priority - IDs (
#header) — very high - Classes, attributes, pseudo-classes (
.box,[type],:hover) — medium - Elements (
h1,p,div) — lowest
#header { color: red; } /* specificity: 0,1,0,0 */
.title { color: blue; } /* specificity: 0,0,1,0 — loses to #header */
h1 { color: green; } /* specificity: 0,0,0,1 — loses to both */
Common mistakes
- Overusing
!important— it breaks the cascade and makes debugging very hard. - Using IDs for styling — prefer classes. IDs are for JavaScript hooks.
- Forgetting that specificity is calculated per selector:
#nav .item a(0,1,1,1) beats.item a(0,0,1,1). - Adding
pxafter0—margin: 0is valid;margin: 0pxworks but0is cleaner.
Quick check below!