三大特性(层叠、继承、优先级)
层叠性
- 就近原则。样式冲突时,执行结构上更近的那个。
- 样式不冲突则不进行层叠,与选择器无关。
继承性
- 子标签会继承父标签的某些样式,例如文本颜色和字号。
优先级
!important > 行内样式 > ID选择器 > 类选择器 > 元素/标签选择器 > 继承/*
计算
| 类型 | 贡献值 |
|---|---|
| 继承或者* | 0000 |
| 元素(标签) | 0001 |
| 类/伪类 | 0010 |
| ID | 0100 |
| 行内样式 | 1000 |
| !importane | 无穷大 |
优先级经典例题
- 例题1:
<style>
/* 两个类选择器 0200 */
#father #son{
color: blue;
}
/* 0111 */
#father p.c2{
color: black;
}
/* 0022 */
div.c1 p.c2{
color: red;
}
/* 继承为0000 */
#father{
color:green !important;
}
</style>
<div id="father" class="c1">
<!-- 最后结果为蓝色 -->
<p id="son" class="c2">
请问这行字是什么颜色
</p>
</div>
- 例题2:
<style>
/* 继承的权重为0 */
#father{
color: red;
}
p{
color: blue;
}
</style>
<div id="father">
<!-- 最后结果为蓝色 -->
<p>请问这行字是什么颜色</p>
</div>
- 例题3
<style>
/* 0002 */
div p{
color: red;
}
/* 0000 */
#father{
color: red;
}
/* 0011 */
p.c2{
color: blue;
}
</style>
<div id="father" class="c1">
<!-- 最后结果为蓝色 -->
<p class="c2">请问这行字是什么颜色</p>
</div>
- 例题4
<style>
/* 0002 */
div div{
color: blue;
}
/* 0001 */
div{
color: red;
}
</style>
<!-- 最后结果为蓝色 -->
<div>
<div>
<div>请问这行字是什么颜色</div>
</div>
</div>
- 例题5
<style>
/* 0011 */
.c1 .c2 div{
color: blue;
}
/* 0101 */
div #box3{
color: green;
}
/* 0101 */
#box1 div{
color: yellow;
}
</style>
<!-- 最后结果为黄色,权重相同采取就近原则-->
<div id="box1" class="c1">
<div id="box2" class="c2">
<div id="box3" class="c3">
请问这行字是什么颜色
</div>
</div>
</div>

浙公网安备 33010602011771号