CSS Specificity and the Cascade

Predict which rule wins when several rules match the same element.

CSS
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
Guided walkthroughReady
1p { color: black; }
2.note { color: blue; }
3p.note { color: green; }
4#intro { color: red; }
5p:first-child { font-weight: bold; }
6a:hover, a:focus-visible { text-decoration: underline; }
7.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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.—
—