๐ŸŽ“ A1Learner
๐Ÿ”

CSS Specificity

Specificity is a score that decides which rule wins when two rules set the same property on one element. The browser compares scores when the rules disagree.

The later rule wins a tie

Two element rules set the same property on the paragraphs. Their scores tie, so the later rule wins.

p {
  color: red;
}
p {
  color: blue;
}

A class beats an element

The class rule comes first here. It still wins on the intro paragraph, because a class scores higher than an element name.

.intro {
  color: green;
}
p {
  color: blue;
}

An id beats an element

The demo paragraph has an id. The id rule scores higher than the element rule, so the id colour wins.

#demo {
  color: purple;
}
p {
  color: blue;
}

Important jumps the queue

The word !important sits after a value. It lifts that declaration above the id rule.

#demo {
  color: purple;
}
p {
  color: blue !important;
}

Example

p {
  color: blue;
}
.intro {
  color: green;
}
#demo {
  color: orange;
}
h1 {
  color: red;
}

Key points

  • Specificity: a score based on the kinds of selectors in a rule
  • An id selector scores higher than a class selector.
  • A class selector scores higher than an element selector.
  • When specificity ties, the later rule in the sheet wins.
  • An inline style beats a rule in a style sheet.
  • The main score counts id selectors, then class selectors, then element selectors.

In this example, the element rule colours every paragraph blue. The class rule then recolours the intro paragraph green, because a class beats an element. The id rule colours the demo paragraph orange, because an id beats both. The heading takes red from its own element rule.

Note

Use !important sparingly, as a last resort for an override that cannot be reached another way.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Two rules set color on one element. One uses a class selector and one uses an id selector. Which rule wins?