I have the following html:
<div class="main">
<div class="container">
<h4 class="test"> Test </h4>
</div>
</div>
And the following CSS:
.main .container h4 {
color: red;
}
.test {
color: blue;
}
Why would the class .test not overwrite the color rule? How can I accomplish this?
Thanks
This is a specificity issue.
Specificity is how important a certain selector is. In this case your first declaration uses two classes, and an element. This means only an inline style, #id or something with more classes can over write it.
If you want to affect the class
test, we can use.main .container .test, this is 3 classes and will now over write it!If two things have the same specificity, for example if you use
.main .container h4again, the one that comes last in the document will take precedence.There is a way to over write regardless of your specificity or where it comes in the document, and that is by adding
!importantto a certain style, for example.test { color: blue !important; }. This is not recommended if you can use what is described above as this may cause future issues.The spec can be found here