Skip to content

选择器的权重

样式的冲突:

当我们通过不同选择器,选择相同的元素,并且为其设置不同的样式(不同的值),此时发生样式冲突。 发生样式冲突时由选择器权重(优先级)决定。(选择器越具体权重越高)

选择器的权重值:

内联样式 优先级:1000 ID选择器 优先级:0100 类和伪元素选择器 优先级:0010 元素选择器 优先级: 0001 统配选择器 优先级:0000 继承的样式 没有优先级 比较优先级时要将所有选择器的优先级进行相加计算,最后优先级越高,越优先显示。(分组选择器是单独计算的) 选择器再累加也不会超过其最大数量级 优先级相同,后面的会覆盖前面的。 例子:

html
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            color: red;

        }
        .red{
            color: white;
        }
/* 这里会优先变为白色 */
    </style>
</head>
<body>
    <div id=box1 class="red">第一个div </div>

</body>
</html>

可以在样式后面加一个!important,则此时该样式会获取到最高的优先级,甚至超过内联样式。 例:

css
<style>
        div{
            color: red !important;

        }
        .red{
            color: white;
        }
</style>
/* 优先变为红色 */