:not选择器未按预期排除元素及相关CSS优先级问题咨询
CSS选择器常见问题解析
先看你给出的代码:
table { margin: 16px; width: 300px; height: 100px; background-color: green; } :not(.exception) table { background-color: red; }
<body> <div class="container"> <table></table> <div class="exception"> <table></table> </div> </div> </body>
问题1::not(.exception) table为何会选中.exception内部的table?
:not(.exception)是匹配所有不属于.exception类的元素,后面的空格是后代选择器,意思是“选中这些元素的所有后代table”。
在你的HTML结构里,body、.container都不属于.exception类,所以它们的所有后代table都会被这个选择器命中——包括.exception内部的table,因为它同时也是body和.container的后代。
另外,这个选择器的优先级(复合选择器,权重10+1)比单纯的table(权重1)高,所以.exception内部的table也会被设置为红色。
问题2:改成.container :not(.exception) table后所有table变绿?
这个选择器的逻辑是:在.container的后代中,找到所有不是.exception的元素,再选中这些元素的后代table。
- 第一个table是
.container的直接子元素,它本身不属于.exception,但它没有后代table,所以不会被选中; .exception内部的table,它的父元素是.exception,而.exception不匹配:not(.exception),所以也不会被选中。
最终这个选择器没有命中任何table,所有table都使用了初始的background-color: green,所以全部变绿。
更好的解决方案
推荐两种清晰且易维护的写法:
写法1:先统一设置,再覆盖例外
先给所有table设置红色,再单独给.exception内部的table恢复绿色,逻辑直观,优先级也足够覆盖:
table { margin: 16px; width: 300px; height: 100px; background-color: red; } .exception table { background-color: green; }
写法2:精确选中目标table
如果只需要给.container的直接子table设置红色,用子选择器>更精准,不会影响嵌套的table:
table { margin: 16px; width: 300px; height: 100px; background-color: green; } .container > table { background-color: red; }
内容的提问来源于stack exchange,提问作者hopgoldy
相关产品推荐
相关产品推荐

