CSS 权重计算

先来放一段代码:

<head>
<style type="text/css">

    h1 em {color:red;}
    h1 > em {color:blue;}

</style>
</head>
<body>

    <h1>This is a <em>important</em> heading</h1>

</body>

结果:

然后我们把css前后交换一下

<head>
<style type="text/css">

    h1 > em {color: blue;}
    h1 em {color: red;}

</style>
</head>

<body>

    <h1>This is a <em>important</em> heading</h1>

</body>

结果:



那么为什么会出现这个情况呢?子代选择器 > 后代选择器 ?

当出现选择器冲突的时候,就要看权重了:

通配选择符 * :000

元素选择器 div :001

子代选择器 ul > li :002

后代选择器  body div p :003    // 几个元素就是几

类选择器 .myClass :010

属性选择器 [type=checkbox] :010

伪类 :nth-child [n] :010 * n

id选择器:#myId :100

相邻兄弟选择器 div + p :002

举例:https://specifishity.com/

注意:input[type=checkbox] == 001 + 010 = 011

X - 0 - 0 : id选择器的数量

0 - Y - 0 : 类选择器,属性选择器,和伪类选择器的数量

*,+,>,~:通配选择器和组合符不会增加权值

当选择器冲突时,权重高的生效;当权重相同时,写在后头的会把前面的覆盖。


现在回到上面的问题,分析一下:

 h1 > em {color: blue;}
 h1 em {color: red;}

这两个选择器权重都是 20,那么写在后面的会把前面的覆盖,即后面的选择器会生效。

猜你喜欢

转载自www.cnblogs.com/javencs/p/10290627.html