css---6 选择器声明的优先级
选择器的特殊性由选择器本身的组件确定,特殊性值表述为4个部分,如 0,0,0,0
一个选择器的具体特殊性如下确定:
1.对于选择器中给定的ID属性值,加 0,1,0,0
2.对于选择器中给定的各个类属性,属性选择,或伪类,加 0,0,1,0
3.对于选择器中的给定的各个元素和伪元素,加0,0,0,1
4.通配符选择器的特殊性为0,0,0,0
5.结合符对选择器特殊性没有一点贡献
6.内联声明的特殊性都是1,0,0,0
7.继承没有特殊性
特殊性 1,0,0,0 大于所有以0开头的特殊性
选择器的特殊性最终都会授予给其对应的声明
如果多个规则与同一个元素匹配,而且有些声明互相冲突时,特殊性越大的越占优势
注意:id选择器和属性选择器
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
width: 200px;
height: 200px;
}
#test{
background: deeppink;
}
.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink{
background: pink;
}
</style>
</head>
<body>
<div class="pink" id="test" style="background: black;">
</div>
</body>
</html>
2 !important
有时某个声明比较重要,超过了所有其他声明,css2.1就称之为重要声明
并允许在这些声明的结束分号之前插入 !important 来标志
必须要准确的放置 !important ,否则声明无效。 !important 总是要放在声明的最后,即分号的前面
标志为 !important的声明并没有特殊的特殊性值,不过要与非重要声明分开考虑。
实际上所有的重要声明会被浏览器分为一组,重要声明的冲突会在其内部解决
非重要声明也会被分为一组,非重要声明的冲突也会在其内部解决
如果一个重要声明与非重要声明冲突,胜出的总是重要声明
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
width: 200px;
height: 200px;
}
div[id].pink{
background: red!important;
}
div[id]{
background: yellow!important;
}
#test{
background: deeppink;
}
.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink.pink{
background: pink;
}
继承:
继承没有特殊性,甚至连0特殊性都没有
0特殊性要比无特殊性来的强
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
color: pink;
}
div{
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="pink" id="test" style="color: black;">
<div>
我是内部的div
</div>
</div>
</body>
</html>
css样式的来源大致有三种
创作人员
读者
用户代理
权重:
读者的重要声明
创作人员的重要声明
创作人员的正常声明
读者的正常声明
用户代理的声明
层叠:
1.找出所有相关的规则,这些规则都包含一个选择器
2.计算声明的优先级
先按来源排序
在按选择器的特殊性排序
最终按顺序
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
width: 200px;
height: 200px;
}
div[class]{
background: deeppink;
}
div.pink{
background: pink;
}
</style>
</head>
<body>
<div class="pink" id="test" >
我是div
</div>
</body>
</html>

浙公网安备 33010602011771号