CSS Specificity and the Cascade
Predict which rule wins when several rules match the same element.
On this page
The concept
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.
Code example
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 code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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. | — | — |
Behind the scenes
How CSS processes this code
The browser matches selectors, computes styles, and paints the result. CSS does not produce console output.