1.首先介紹一下CSS行內
行內css也叫做行級css或行內css,它是直接在標簽內使用
1 <body> 2 <span style="color: red;">我是span塊</span> 3 </body>
2.各種選擇器
標簽選擇器:點擊 這里 了解標簽選擇器
ID選擇器:點擊 這里 了解ID選擇器
類選擇器:點擊 這里 了解類選擇器
屬性選擇器:點擊 這里 了解屬性選擇器
偽類:點擊 這里 了解偽類
偽元素:點擊 這里 了解偽元素
3.進入主題,了解選擇器優先級計算公式
每位寫過各種選擇器的學習者來說,都總結過一個大眾的規律:
行內>ID選擇器>類選擇器>標簽選擇器
其實關于優先級有一個計算公式,在《CSS REFACTORING》一書中提過
A specificity is determined by plugging numbers into (a, b, c, d):
- If the styles are applied via the style attribute, a=1; otherwise, a=0.
- b is equal to the number of ID selectors present.
- c is equal to the number of class selectors, attribute selectors, and pseudoclasses present.
- d is equal to the number of type selectors and pseudoelements present.
什么意思呢?我給大家解讀一下
優先級是通過將數字插入(a,b,c,d)中來確定的:
- 如果行內樣式屬性應用樣式,則a = 1; 否則,a = 0,
- b等于存在的ID選擇器的數量,
- c等于存在的類選擇器,屬性選擇器和偽類的數量,
- d等于存在的標簽選擇器和偽元素的數量,
(現在知道上面科普各類選擇器的意義了吧0.0),說了這么多還是有人看不明白,直接上個例子吧
1 <style> 2 #div1 .a1 {color: red;} 3 #div1 .a1:link {color: blue;} 4 .div1 .a1 {color: yellow;} 5 .a2 {color: red;} 6 </style> 7 8 <body> 9 <div id="div1" class="div1">我是一個div 10 <a href="#" class="a1">鏈接</a> 11 </div> 12 <a href="#" class="a2">鏈接</a> 13 </body>
#div1 .a1對應的(a,b,c,d)a=0,b=1,c=1+0+0=1,d=0,故(0,1,1,0)
#div1 .a1:link對應的(a,b,c,d)=(0,1,2,0),所以比#div1 .a1優先級高
同理 .div1 .a1=(0,0,2,0),所以比#div1 .a1優先級低
現在大家一目了然,應該不會有css加載優先級的問題了,有問題可以發郵件,[email protected]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/65686.html
標籤:Html/Css
