今天我们来聊一下css权重
,这个问题在面试中也经常遇到,但是我们可能对他有一些误解~
我们理解的权重
常见的最简单的权重记法:
1 2 3 4
| `!important`是`1000` `id`选择器是`100` `class`选择器是`10` `tag标签`选择器是`1`
|
我们认为的权重
10个tag选择器
的权重就要大于class选择器
的权重了
10个class选择器
的权重就要大于id选择器
的权重了
10个id选择器
的权重就要大于!important
的权重了
实际上的权重
但是,实际不是上面描述这样的,可能会有很多人会这样认为,上面这段只是协助大家理解权重,实际上无论多少个class选择器都不会大于一个id选择器的权重,同理id选择器和!important的关系也是这样
上代码
可以看下效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>css权重测试</title> <style type="text/less" lang="less"> .info{ width: 500px; height: 500px; background-color: yellow; div{ background-color: red; width: 200px; height: 200px; }
.item1.item2.item3.item4.item5.item6.item7.item8.item9.item10.item11{ background-color: #000; } #item{ background-color: blue; } } </style> </head>
<body> <div class="info"> <div id="item" class="item1 item2 item3 item4 item5 item6 item7 item8 item9 item10 item11"> 这里是内容 </div> </div> <script src="https://cdn.bootcdn.net/ajax/libs/less.js/4.1.1/less.js"></script> </body> </html>
|
运行结果