css樣式的優先級分為引入優先級和聲明優先級。
引入優先級
引入樣式一般分為外部樣式,內部樣式,內聯樣式。
外部樣式:使用link引入的外部css文件。
內部樣式:使用style標簽書寫的css樣式。
內聯樣式:直接書寫在html標簽里面的css樣式。
優先級如下:
內聯樣式 > 外部樣式 = 內部樣式
外部樣式優先級和內部樣式優先級相同,故寫在后面的樣式會覆蓋前面的樣式。
聲明優先級
一般優先級如下:
- !important > 內聯 > ID > Class|屬性|偽類 > 元素選擇器
- :link、:visited、:hover、:active 按照LVHA順序定義
優先級算法:
等級 | 內聯選擇器 | ID選擇器 | 類選擇器/屬性選擇器/偽類 | 元素選擇器 |
---|---|---|---|---|
示例 | <span style="color:red;"></span> | #sp{color:red} | .sp{color:red} [type="text"]{color:red} :nth-of-type(1){color:red} | span{color:red} |
優先級 | 1-0-0-0 | 0-1-0-0 | 0-0-1-0 | 0-0-0-1 |
注意:
**通配符 * 的優先級為 0-0-0-0,但是優先級大于繼承樣式優先級。++
優先級算法示例:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><style>a{color: yellow;} /*特殊性值:0,0,0,1*/div a{color: green;} /*特殊性值:0,0,0,2*/.demo a{color: black;} /*特殊性值:0,0,1,1*/.demo input[type="text"]{color: blue;} /*特殊性值:0,0,2,1*/.demo *[type="text"]{color: grey;} /*特殊性值:0,0,2,0*/#demo a{color: orange;} /*特殊性值:0,1,0,1*/div#demo a{color: red;} /*特殊性值:0,1,0,2*/</style>
</head><body><a href="">第一條應該是黃色</a><div class="demo"><input type="text" value="第二條應該是藍色" /><a href="">第三條應該是黑色</a></div><div id="demo"><a href="">第四條應該是紅色</a></div>
</body></html>