开发者

Is the order of rules within a single css file important?

Does the order of the rules within a single css file make a difference?

<div id="wrapper>
    <div id="a>
        section a
    </div>
    <div id="b>
        section b
    </div>
    <div 开发者_StackOverflow中文版id="c>
        section c
    </div>
</div>

Can the div rule for #c need to be below #a and #b, or will the clear:both not work?

#wrapper {
color: #CCC;
}

#c {
clear:both
}

#a {
float: right;
}

#b {
float: left;
}


Order is indeed important.

See http://msdn.microsoft.com/en-us/library/aa342531%28VS.85%29.aspx#specf

To quote, in part:

3. Sort by specificity of selector: selectors with higher specificity override selectors that are more general. Specificity is calculated by concatenating the count of (a) ID attributes, (b) class and pseudo-class attributes, and (c) type names and pseudo-elements in the selector.

For example, each of the following selectors could apply to a single LI element; however, only declarations with the highest specificity are applied in the event of a conflict.

*             {}  /* a=0 b=0 c=0 -> specificity =   0 */  
li            {}  /* a=0 b=0 c=1 -> specificity =   1 */  
ul li         {}  /* a=0 b=0 c=2 -> specificity =   2 */ 
li:first-line {}  /* a=0 b=0 c=2 -> specificity =   2 */
ul ol+li      {}  /* a=0 b=0 c=3 -> specificity =   3 */
li.class      {}  /* a=0 b=1 c=1 -> specificity =  11 */
li#id         {}  /* a=1 b=0 c=1 -> specificity = 101 */ 

4.Sort by order specified: if two rules have the same weight and specificity, the last one parsed wins. (Note that stylesheets specified with an @import rule are parsed first.) Selectors that appear later in the stylesheet will be used if there is any conflict. For this reason, link pseudo-class selectors should always be used in the following order.

Also see http://www.smashingmagazine.com/2009/08/17/taming-advanced-css-selectors/ for a broader description with more examples.

Note that since there is no overlap in your example, the order is not important. If, on the other hand, you had conflicting styles, then weight, specificity and order would be relevant. I assume that your example in the question is rather simplified.


Order only matters if the rules apply to the same attribute of the same element. (In that case, the last rule "wins".) In your example, the order will make no difference.


In the event of equally specific rules that apply to the same element, the later one wins.

If you have the style:

.foo { color: red; }
.bar { color: blue; }

And the markup:

<div class="foo bar">Test</div>

Then the text in the div will be colored blue. If you switch the order of the rules, it will be red.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜