Specificity
Let's take a deep dive into CSS specificity.
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.
We have an element that is both an ID & class selector target. In this case, the ID selector has a higher specificity. Meaning the style of the ID selector will apply instead of any style set by the class selector.
For example, say you want all your button elements to have a blue color. You could use a class selector to define all elements under the button class to have a blue background color (hex color code #14288A) and a white font color (#FFFFFF). But you want to have a subscribe button to be an exception to this rule (so it stands out!). Then you could use an ID selector to define the specific button with the ID (e.g., "homepage”) to have an orange background color (#F59100) and a black font color (#000000). All other button elements that don’t have the ID “homepage” will still follow the CSS rule of the class selector.
Example
Get hands-on with 1400+ tech skills courses.