tags:

views:

90

answers:

3

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?

+6  A: 

Styles are applied according to which styles are most specific to the element, and then in textual order. More here in the spec. Because a:link is more specific than ul li a, that style wins regardless of placement.

T.J. Crowder
The actual reason is that `a:link` is more specific than `ul li a`.
David Dorward
@David: Quite! Yeah, I kinda dropped the beginning of that, didn't I? Fixed.
T.J. Crowder
+1  A: 

I'd use color:blue !important;

c0mrade
There are two problems with this. First, you got the syntax wrong (the bang comes before the word important). Second, it is the sledgehammer approach and there is no coming back. If you have a third style you want to put into the cascade, then !important is going to knock it over too.
David Dorward
@David Dorward Thank you, I corrected it. I was just answering to his question `So tell me, how must I correct my style to achieve the a tag inside the li to be rendered blue and not red?` was I not, he didn't say anything about third style did he now :D Its very ugly I agree but it answers his question
c0mrade
Can downvoter tell me why the downvote, I fixed the syntax error, what else must I fix/explain/or not
c0mrade
+2  A: 

Here's an article about CSS Selector specificity which looks good: http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

The section in How to measure specificity? gives you the answer:

a:link   => one tag (a) + one pseudo-class (:link) = 1 + 10    = 11 points
ul li a: => three tags (ul, li, a)                 = 1 + 1 + 1 =  3 points

So the a:link style wins.

Hint: Order (in the CSS files) only matters when two css selectors have the same specificity.

Douglas