CSS 渲染样式优先级(选择器优先级)

原创
2015/11/28 10:09
阅读数 115

To find the value for an element/property combination, user agents(浏览器) must apply the following sorting order:(浏览器渲染遵循的规则如下:)

    

     1、Find all declarations that apply to the element and property in question, for the target media type. Declarations apply if the associated selector matches the element in question and the target medium matches the media list on all @media  rules containing the declaration and on all links on the path through which the style sheet was reached.

        找到所有样式


     2、Sort according to importance (normal or important) and origin (author, user, or user agent). In ascending order of precedence:

    1. user agent declarations(浏览器)

    2. user normal declarations(浏览用户)

    3. author normal declarations(开发人员样式)

    4. author important declarations

    5. user important declarations

           按照样式来源进行优先级排序(升序)


     3、Sort rules with the same importance and origin by specificity of selector: more specific selectors will override more general ones. Pseudo-elements and pseudo-classes are counted as normal elements and classes, respectively.

               按选择器的优先级排序


     4、Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.

         以上优先级相同时,后来者居上,但是文档中 style标签中的样式优先级会优先于引入的样式表。




Calculating a selector's specificity

A selector's specificity is calculated as follows:

  • count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)

  • count the number of ID attributes in the selector (= b)

  • count the number of other attributes and pseudo-classes in the selector (= c)

  • count the number of element names and pseudo-elements in the selector (= d)

Some examples:

 *             {}  /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */
 li            {}  /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */
 li:first-line {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
 ul li         {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
 ul ol+li      {}  /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */
 h1 + *[rel=up]{}  /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
 ul ol li.red  {}  /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */
 li.red.level  {}  /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */
 #x34y         {}  /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
 style=""          /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */


附:浏览器默认样式表

http://developer.doyoe.com/default-style/ 

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部