否定伪类选择器[:not()]未能按预期工作[重复]

问题描述 投票:0回答:2

在下面的示例中,我希望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>

为什么该否定选择器在本示例中未按预期工作?

html css css-selectors
2个回答
2
投票

[您需要在伪类前面放置一个选择器,例如如果您需要section:not(.green) .red > p,则伪类是添加到选择器的关键字。


1
投票

您需要添加根选择器而不是。

.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>
© www.soinside.com 2019 - 2024. All rights reserved.