文章目錄
- CSS三大特性
-
- 繼承性
- 層疊性
- 優先級
-
- 權重計算
CSS三大特性
CSS有三個特性:
- 層疊性
- 繼承性
- 優先級
繼承性
CSS的繼承性指的是子元素繼承了父元素的某些樣式屬性。
具有繼承性的屬性有三大類:
- 文本相關屬性:font-family、font-size、font-style、font-weight、font、line-height、text-align、text-indent、word-spacing。
- 清單相關屬性:list-style-image、list-style-position、list-style-type、list-style;
- 顔色相關屬性:color。
層疊性
CSS的層疊性,指的就是樣式的覆寫。
CSS會以最後定義的屬性的值為準;也就是“就近原則”原則。
就近原則三個條件:
- 元素相同。
- 屬性相同。
- 權重相同。
優先級
當同一個元素的同一個樣式屬性被設定多個屬性值時,就會有優先級的産生。
選擇器 | 權重 |
---|---|
繼承或 * | 0,0,0,0 |
元素選擇器 | 0,0,0,1 |
類選擇器,僞類選擇器 | 0,0,1,0 |
id選擇器 | 0,1,0,0 |
行内樣式 style=“” | 1,0,0,0 |
!important | 無窮大 |
權重計算
!important > id權重 > class權重 > 元素權重
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
/*權重:(2,0,1)*/
#box1 #box2 p {
color: red;
}
/*權重:(2,1,1)*/
#box1 .box2 #box3 p {
color: green;
}
/*權重:(0,3,1)*/
.box1 .box2 .box3 p {
color: blue;
}
</style>
</head>
<body>
<div id="box1" class="box1">
<div id="box2" class="box2">
<div id="box3" class="box3">
<p>hello</p>
</div>
</div>
</div>
</body>
</html>
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLxADZ4YzN5UzNjJWNmRGZiNGZlRDMlVTOmBjM0YmY5IzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)