I have the following HTML.
<ul>
<li>
<a>asdas</a>
</li>
</ul>
In my CSS stylesheet I have general settings for the a tag, and several hundered lines later settings for ul li a.
Like this:
a:link
{
color: red;
}
...
ul li a
{
color:blue;
}
Firebug tells me, that first the color:blue is loaded, and afterwards overriden by color:red
So far I’ve always thought, that the order of loading css files and the order of style inside a single css file tell the browser how html elements should be formatted. Unfortunately I’m now experiencing it vice versa.
So tell me, how must I correct my style to achieve the a tag inside the li to be rendered blue and not red?
Styles are applied according to which styles are most specific to the element; among rules that have equal specificity, the last matching rule in the CSS text wins. (There’s also a new concept of "layers" I won’t go into here.) More in the spec. Because
a:linkis more specific thanul li a, that style wins regardless of placement.For the purposes of calculating specificity, the browser (and other tools that process CSS) use numbers with three columns:
.class(a class selector),:hover(a pseudo-class selector), and attribute selectors like[type=button]aorulas well as::beforeand suchEach column is more significant than the one after it (just like in decimal numbers, where in the number
123, the1is more signfiicant than the2, which is more significant than the3).a:linkcomes out as 0-1-1 because it doesn’t have any ID selectors, has one class selector (:link), and has one type selector (a).ul li acomes out as 0-0-3, because it doesn’t have any ID or class selectors, but has three type selectors. 0-1-1 is more specific than 0-0-3 because the leading 0s are the same, but 0-1-1 has a 1 in the second column where 0-0-3 only has a 0 (so we ignore the third column, since the second column is more significant than the third).Make the blue rule at least as specific as the red rule. In this case, you can do that by adding
:linkto it: