I am confused about a simple behaviour of CSS.
I have some <a class="cool-element"></a> elements in the DOM, and no other types of elements in the dom have the `”cool-element” class, not even the divs. So I did this to try to select them:
.cool-element {
background-color: red;
}
that to my surprise did not work. But if I do
a.cool-element {
background-color: red;
}
I get the expected result. I test this in Firefox and in an app that has a lot of other CSS rules loaded. I haven’t tested this in isolation, but I am pretty sure in some other places I am using the first selector with success. Isn’t the first selector here supposed to work perfectly fine all the times, or am I missing something?
CSS specificity
In CSS more specific rules take precedence over less specific rules. You can calculate the specificity of a given selector using the following
A selector overrides all selectors with less point than it. If they have the same number of points then order matters.
Examples
Until I learned how the points are calculated CSS was a dark art in my mind. There is a good article on css-tricks which might do a better job of explaining it – jump to the Calculating CSS Specificity Value section
Order matters
As Jorge Alvarado mentioned order matters, so if you have two rules that apply to the same elements, the second style will override the first one.