CSS Specificity and the Cascade
Predict which rule wins when several rules match the same element.
p { color: black; }
.note { color: blue; }
p.note { color: green; }
#intro { color: red; }
p:first-child { font-weight: bold; }
a:hover, a:focus-visible { text-decoration: underline; }
.card > h2 + p { margin-top: 0; }Explanation
When several rules set the same property, the cascade decides which one wins. A rule with higher specificity beats one with lower specificity, whatever their order. Specificity is counted as three numbers: ids, then classes, attributes, and pseudo-classes, then element names. An id selector beats any number of class selectors, and a class beats any number of element selectors. When specificity is equal, the rule that appears later wins. Avoid !important and long selector chains, and prefer low-specificity class selectors so that styles stay easy to override.
Explore the dry run
p { color: black; }.note { color: blue; }p.note { color: green; }#intro { color: red; }p:first-child { font-weight: bold; }a:hover, a:focus-visible { text-decoration: underline; }.card > h2 + p { margin-top: 0; }Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Specificity (0,0,1): one element selector. | — | — | |
| Specificity (0,1,0): one class beats any number of element selectors. | — | — | |
| Specificity (0,1,1): a class plus an element, so it beats .note on a p with class note. | — | — | |
| Specificity (1,0,0): an id beats every class selector. | — | — | |
| A pseudo-class counts like a class: (0,1,1). | — | — | |
| A selector list applies one block to both selectors. Include focus-visible so keyboard users get the same cue as mouse users. | — | — | |
| Combinators: the child combinator > and the adjacent sibling combinator + do not add specificity themselves. | — | — |