# CSS 层叠性

作者:刘小标 时间:2020-01-14

# 1 什么是 CSS 层叠性?

层叠性是指有多个选择器或一个选择器中的多条样式作用于同一元素,即样式的作用范围发生了重叠。

划重点:层叠性,就是 CSS 处理冲突的能力,也就是在页面渲染线中样式计算(Recalculate Style)过程中,每个节点合并来自多个源的属性值的算法。

# 2 样式无冲突

<style>
  /* 多个选择器选择同一个元素,样式并无冲突时 */
  .box_one {
    width: 100px;
    height: 100px;
  }
  .box_two {
    background: red;
  }
</style>
<body>
  <div class="box_one box_two"></div>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13

详解: 以上代码中,样式代码并无冲突,两个选择器中的所有样式都叠加到了元素 div 上,div 最终呈现的是一个红色的,宽高度大小为 100px 的容器。

# 3 样式冲突

# 3.1 样式有冲突,同一级别不受优先级影响时

.box_one{ width:100px; height:100px; } .box_two{ width:200px; background:red; }
<body>
  <div class="box_one box_two"></div>
</body>
1
2
3
4

详解: 以上代码中,在同级别时(同个元素,同是 class 定义选择器名称),样式代码出现冲突,两个选择器中出现同一条 width 属性,则以 CSS 代码中最后出现的那条样式为准,div 最终呈现的是一个 width 为 200px,height 为 100px,红色的容器。

# 3.2 样式有冲突,不同级别受优先级(权重)的影响时

选择器权重排序:

选择器 样例 权重
通配符 如:* 0
伪元素 如::first-line,:first-letter,:before,:after 1
元素选择器 如:div,p,h2 1
class 选择器 如:.dist,.employee 10
伪类 如::active,:focus,:hover,:link,:visited,:lang, :first-child 10
属性选择器 如:p[attribute=value],p[attribute~=value],p[attribute|=value],p[attribute$=value]、p[attribute*=value] 10
id 选择器 如:#dist 100
行内选择器 如:<p style="color:red">行内</p> 1000
# 3.2.1 类别(class)样式 VS 元素(标记)样式
.box_one{ width:200px; background:red; } div{ width:100px; height:100px; }
<body>
  <div class="box_one"></div>
</body>
1
2
3
4

详解: 以上代码中,class 样式的优先级大于元素样式的优先级,即使 div 设置的 width 写在后面,最终呈现的是一个 width:200px,height:100px;背景色为红色的容器。

# 3.2.2 ID 样式 VS 类别(class)样式
#box{ width:200px; background:yellow; } .box_one{ width:100px; height:100px;
background:red; }
<body>
  <div class="box_one" id="box"></div>
</body>
1
2
3
4
5

详解: 以上代码中,ID 样式的优先级大于 class 样式的优先级,最终呈现的是一个 width:200px,height:100px;背景色为黄色的容器。

# 3.2.3 行内样式 VS ID 样式
#box{ width:200px; background:yellow; } .box_one{ width:100px; height:100px;
background:red; }
<body>
  <div class="box_one" id="box" style="background:pink"></div>
</body>
1
2
3
4
5

详解 以上代码中,CSS 行内样式优先于 ID 的样式,div 最终呈现的是一个宽度为 200px,高度 100px,背景颜色为粉色的容器。

# 3.2.3 !important VS 行内样式
.box_one{ width:100px!important; height:100px; background:red!important; } #box{
width:200px; }
<body>
  <div class="box_one" id="box" style="background:pink"></div>
</body>
1
2
3
4
5

详解: 在 CSS 中,!important 具有最高优先级,并且可以写在任意一条有冲突样式的后面。在以上代码中,div 在行内样式表设置背景色为粉色,ID 样式中 width 为 200px;但是在 class 样式中,width:100px 及背景色为 red 的后面都添加了!important,因此,最终呈现的是一个宽度为 100px,高度为 100px,背景色为红色的容器。