疑问:为何CSS :not(p)选择器会作用于<p>元素?
为什么
:not(p)会让<p>文字变红? 问题核心出在CSS继承特性和:not()的匹配范围上:
你的:not(p)选择器会匹配所有不是<p>的元素,包括<html>、<body>这些页面根元素。而color是可继承的CSS属性,<body>被选中后设置了红色,<p>作为它的子元素,会自动继承这个颜色样式,所以看起来<p>的文字也变红了。
你的代码示例
:not(p) { color: #ff0000; }
<h1>This is a heading</h1> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <div>This is some text in a div element.</div> <a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>
解决办法
如果你只想让<h1>、<div>、<a>显示红色,直接指定这些元素更直接:
h1, div, a { color: #ff0000; }
或者用:is()简化写法:
:is(h1, div, a) { color: #ff0000; }
要是非要用:not(),得限制它只匹配你目标的元素类型,避免根元素被选中:
h1:not(p), div:not(p), a:not(p) { color: #ff0000; }
关键提醒
:not()只是排除指定元素,但无法阻止CSS的继承规则。只要被:not()选中的元素是<p>的父级,<p>就会继承它的样式属性。
内容的提问来源于stack exchange,提问作者Paras Chandravanshi
相关产品推荐
相关产品推荐

