I am trying to understand specificity in CSS.
My current understanding is that specificity is very similar to inheritance, but in some way more specifically defined.
Mozilla Specificity Definition:
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of CSS selectors of different sorts.
The current task is:
Refactor the CSS declarations for .active a
and .copyright
so that the !important
rule can be removed.
CSS:
.main li a {
color: #7ab2c1;
}
.active a {
color: #826c55 !important;
}
.primary p {
font-size: 12px;
}
.copyright {
font-size: 10px !important;
}
And relevant HTML:
<nav class="main">
<ul class="group">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
[...]
<footer class="primary">
<p><a href="#">Sign up</a> for our newsletter, it's a racket!</p>
<p class="copyright">Copyright © Sven's Snowshoe Emporium. All Rights Reserved.</p>
</footer>
Can anyone guide me through the process of refactoring in such a way that helps me to grasp the fundamental concepts?
A class has a specificity of 10. An element has a specificity of 1.
Therefore, in the first instance:
.main li a
selector has a specificity of 12..active a
selector has a specificity of 11Because they both target the same element, and the former has a higher specificity, the latter loses the battle to style the element.
In the second instance:
.primary p
selector has a specificity of 11..copyright
selector has a specificity of 10.Again, because they both target the same element, and the former has a higher specificity, the latter loses the battle to style the element.
The !important
annotation trumps all specificity. Hence, with that applied, .active a
and .copyright
re-take the elements.
If you want to remove !important
, which would be the right thing to do as it's not necessary here, you can instead boost the specificity of the selectors.
An ID
has a specificity of 100. So that can quickly move a selector up in priority.
Here are some examples:
.main li a { color: #7ab2c1; } /* previous winner; specificity 12 */
.main .active a { color: #ff0000; } /* added class selector; specificity now 21 */
.primary p { font-size: 12px; } /* previous winner; specificity 11 */
#copyright { font-size: 8px;} /* switched to ID selector; specificity now 100 */
<nav class="main">
<ul class="group">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<footer class="primary">
<p><a href="#">Sign up</a> for our newsletter, it's a racket!</p>
<p id="copyright">Copyright © Sven's Snowshoe Emporium.
All Rights Reserved.</p>
</footer>
References: