在下面的示例中,我希望all p
元素以green背景呈现,因为red背景仅应在.red
类为not .green
类的后代。然而,事实并非如此。
.green p {
background: green;
}
:not(.green) .red > p {
background: red;
}
<section class="green">
<p>Neutrum vero, inquit ille. Et nemo nimium beatus est; Age, inquies, ista parva sunt. Haec para/doca illi..
<p/>
<div class="red">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Hoc enim constituto in philosophia constituta sunt omnia. Num quid tale Democritus..</p>
<p>Zenonis est, inquam, hoc Stoici. Certe, nisi voluptatem tanti aestimaretis. Erat enim Polemonis. Tanta vis admonitionis inest in locis.</p>
<p>Age sane, inquam. Omnis enim est natura diligens sui. Duo Reges: constructio interrete. Quid ergo attinet gloriose loqui.</p>
</div>
<p>Pro consul accusata id, errem nonumy assentior qui et. Quem albucius omittantur id sea, duo cu posse insolens.
<p/>
</section>
为什么该否定选择器在本示例中未按预期工作?
[您需要在伪类前面放置一个选择器,例如如果您需要section:not(.green) .red > p
,则伪类是添加到选择器的关键字。
您需要添加根选择器而不是。
.green p {
background: green;
}
root:not(.green) .red > p {
background: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<section class="green">
<p>Neutrum vero, inquit ille. Et nemo nimium beatus est; Age, inquies, ista parva sunt. Haec para/doca illi..
<p/>
<div class="red">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Hoc enim constituto in philosophia constituta sunt omnia. Num quid tale Democritus..</p>
<p>Zenonis est, inquam, hoc Stoici. Certe, nisi voluptatem tanti aestimaretis. Erat enim Polemonis. Tanta vis admonitionis inest in locis.</p>
<p>Age sane, inquam. Omnis enim est natura diligens sui. Duo Reges: constructio interrete. Quid ergo attinet gloriose loqui.</p>
</div>
<p>Pro consul accusata id, errem nonumy assentior qui et. Quem albucius omittantur id sea, duo cu posse insolens.
<p/>
</section>
</body>
</html>