Search⌘ K
AI Features

Specificity

Explore how CSS specificity determines which style rules apply when multiple selectors target the same element. Understand the calculation of specificity across type, class, id, and inline selectors, and learn best practices for managing style precedence without relying on !important declarations.

Specificity

When multiple CSS rules target an element, specificity comes into play.

For example, let’s see the following element:

<p class="surname">
Smith
</p>

We could have one rule selecting our class:

.surname {
color: red;
}

And another rule targeting p, which sets the color to a different value:

p {
color: green;
}

And we could even have another rule targeting p.surname.

So which rule will take precedence over the others, and why?

This is where the rules of specificity come into consideration. The more specific rule will always win. And if two or more rules have the same specificity, the one that appears last wins.

For example, if an element is targeted by both an ID and a class selector, the ID selector has higher specificity, meaning the style from the ID selector will apply instead of any style set by the class selector.

Imagine you want all button elements to have a blue background color and white font color. But you want a subscribe button to be an exception. ...