<html data-theme="light">
...
<div class="stop-icon">
<span class="text">TEST</span>
</div>
...
</html>
.stop-icon .text { color : #green }
[data-theme='light'] .text { color : #red } // 实际生效
stop-icon 离 text 更近,为什么没有生效呢?
因为属性选择器 [data-theme='light'] 和类选择器 .stop-icon 优先级相同,优先级计算会无视DOM树中的距离,所以写在后面的会覆盖写在前面的选择器。
所以想让 stop-icon 生效,只要把stop-icon的选择器优先级设置的更高。比如 id=“stop-icon”,内联样式,! important 。
下面是优先级规则是递增的:
- 元素选择器(例如,
h1)和伪元素(例如,::before) - 类选择器 (例如,
.example),属性选择器(例如,[type="radio"])和伪类(例如,:hover) - ID 选择器(例如,
#example) - 内联样式
-
! important