为同一个p元素设置id为intro与class为bb,对他们进行不同颜色设置,结果应用了针对id设置时显示的颜色
<html>
<head><style type="text/css">
p{color:red}
#intro {color:green}
.bb{color:black}
</style>
</head>
<body>
<p id="intro" class=“bb">This is a paragraph of introduction.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>...</p>
</body>
</html>
结果:
总结:
CSS样式选择器分为4个等级,a、b、c、d,可以以这四种等级为依据确定CSS选择器的优先级。
1.1!important 权重最高,比 inline style 还要高 ,是最高权重
(w>a)
2.如果样式是行内样式(通过Style=””定义),那么 (w=a)
3.ID选择器 (w=b)
4.Class类选择器 (w=c)。
5.类型选择器 (w=d)
6.属性选择器,伪类选择器和class类选择器优先级一样 (w=c),伪元素选择器和类型选择器一样 (w=d)
2.如果样式是行内样式(通过Style=””定义),那么 (w=a)
3.ID选择器 (w=b)
4.Class类选择器 (w=c)。
5.类型选择器 (w=d)
6.属性选择器,伪类选择器和class类选择器优先级一样 (w=c),伪元素选择器和类型选择器一样 (w=d)
- 通配选择符的权值 0,0,0,0
- 标签的权值为 0,0,0,1
- 类的权值为 0,0,1,0
- 属性选择的权值为 0,0,1,0
- 伪类选择的权值为 0,0,1,0
- 伪对象选择的权值为 0,0,0,1
- ID的权值为 0,1,0,0
- important的权值为最高 1,0,0,0
使用的规则也很简单,就是 选择器的权值加到一起,大的优先;如果权值相同,后定义的优先 。虽然很简单,但如果书写的时候没有注意,很容易就会导致CSS的重复定义,代码冗余。
从上面我们可以得出两个关键的因素:
- 权值的大小跟选择器的类型和数量有关
- 样式的优先级跟样式的定义顺序有关