CSS選擇符及優先順序計算

來源:互聯網
上載者:User

行內樣式(Inline Style),如<span style="color:red">...</span>;
ID選擇符(ID selectors),如#myid;
類、屬性選擇符、偽類(Classes, attributes and pseudo-classes),如 .class {...}、[href$=dudo.org]、:hover;
類型(elements)、偽類型選擇符(pseudo-elements),如 p {...}、:first-line {...};

他們的優先順序怎麼來測量呢?如前所述,它們每一類都有不同的數值表示,其中:
行內樣式為:1000
ID選擇符為:0100
類選擇符為:0010
類型選擇符為:0001
這裡要指出的是,所有這些數值都不是10進位數字,1000隻是代碼,它是一個行內樣式,

例如,body #wrap p {...},那麼它的優先順序指數就是 1+100+1=102,而body div #wrap p {...}的優先順序指數就是 1+ 1 +100 + 1 =103。
再看一下其它的例子:
* { } 0
li:first-line { }      2 (one element, one pseudo-element)
ul ol+li { }           3 (three elements)
ul ol li.red { }     13 (one class, three elements)
style=””        1000 (one inline styling)
div p { }                2 (two HTML selectors)
div p.sith { }      12 (two HTML selectors and a class selector)
body #darkside .sith p { }    112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)

看這段代碼:
<html>
<head>
<style type="text/css">
       #wrap #content {color: blue;}
       #content {color: red;}
</style>
</head>
<body>
<div id="wrap">
      <div id="content">this is a text here</div>
</div>
</body>
</html>
代碼將顯示藍色。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.