学习css之选择器优先级

时间:2023-03-09 16:11:19
学习css之选择器优先级

相信每一位前端工作者最开始迷惑的地方便是界面展示为什么不符合预期效果呢,下面我来介绍一下可能引起上面结果的原因之一——css优先级。

我这里采用对照法来得出结论,代码如下:

<style>
/*伪元素与id选择器*/
#p1 {
background: red;
height: 30px;
}
p:before {
content: "你好";
background: gray;
}
/*内联样式与伪类*/
a:hover {
background: red;
}
/*id与伪类比较*/ #input1 {
background: grey;
}
input[type="button"]:active {
background: red;
}
/*伪类与属性选择器比较*/ input[type="text"]:focus {
background: gray;
}
input[type="text"] {
background: red;
}
/*属性与类比较*/
a[href] {
background: gray;
}
.label2 {
background: red;
}
/*类与标签比较*/
.label1 {
background: gray;
}
label {
background: red;
}
</style> <body>
<p style="background: gray;">
内联样式与伪元素
</p>
<p id="p1">
伪元素与id
</p>
<div>
<input type="button" id="input1" value="id与伪类"></input><br />
<input type="text" placeholder="伪类与属性" /><br />
<a href="#input1" class="label2">属性与类</a><br />
<label class="label1">类与标签</label>
</div>
</body>

界面如下:

学习css之选择器优先级

灰色代表优先级高的,红色表示优先级低的,可得结论:内联样式》伪元素》id》伪类》属性》类》标签

以上是单一的形式对比,如果出现多个选择器合在一起,那么使用四则运算就好了抛开伪元素不谈,那么内联为千位,id为百位,伪类/属性/类为十位,标签为个位。

十位中再细分三位,与哪个位置的选择器匹配,则哪个位置+1 比较最终的数值就好。