Demo
Summary
In CSS, selectors with higher specificity will override selectors with lower specificity when they are modifying the same properties. The order of specificity from lowest to highest is type selector, class selector, and ID selector.
Details
In CSS, different selectors have different levels of specificity. Selectors with higher specificity will override selectors with lower specificity when they are modifying the same properties. The order of specificity from lowest to highest is type selector, class selector, and ID selector.
Let’s say you had the following paragraph element in your HTML file with an ID and a class:
<p id="my-id" class="my-class">Test paragraph.</p>
Let’s say you also have the following CSS code:
#my-id {
color: red;
}
.my-class {
color: green;
}
p {
color: blue;
}
Even though the type selector is last, the ID selector has a higher level of specificity and will be applied to the paragraph element, and the paragraph text will be red. If there was no ID selector then the class selector would kick in and the text would be green.
Exercises
First, recreate the CSS code in the embedded CodePen demo. Try commenting out the different CSS rules to see the effect on the web page. Then try customizing the final color
value.
References
Specificity on MDN