开发者

In which order are CSS styles applied?

开发者 https://www.devze.com 2022-12-29 23:22 出处:网络
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 settin

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, and then in textual order for rules that have equal specificity. More here in the spec. Because a:link is more specific than ul li a, that style wins regardless of placement.

So tell me, how must I correct my style to achieve the a tag inside the li to be rendered blue and not red?

Make the blue rule at least as specific as the red rule. In this case, you can do that by adding :link to it:

ul li a:link
{
  color:blue;
}


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.


I'd use color:blue !important;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号