如何将 css 类应用于元素但排除相同样式的嵌套/子元素

Hai*_*iri 2 css

您好,我正在尝试将样式应用于主体元素,但样式不应影响选择器指定的嵌套元素。我尝试过,:not但它似乎不适用于儿童元素。这是我的例子:

<!DOCTYPE html>
<html>
<head>
<style>
body:not(.not-disabled) {
  color: #ff0000;
  opacity: 0.4;
  pointer-events: none;
}
</style>
</head>
<body>

  <h1>This is a heading</h1>

  <p class="not-disabled">This is a paragraph.</p>
  <p class="not-disabled">This is another paragraph.</p>
  <button class="not-disabled">Enabled</button>
  <button>Disabled</button>
  <div>This is some text in a div element.</div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我希望这些段落不透明。另外,这两个按钮都被禁用,但我想启用其中之一,即:Ebabled,但我的期望结果是不正确的。

有什么办法可以做到这一点吗?请不要对我评价太严厉。我是 CSS 新手,我用 google 搜索但找不到解决方案。可能作为一个新手,我的问题是错误的。

Lin*_*TED 5

body:not(.not-red)意味着样式应该应用于没有.not-red类的主体元素。

您正在寻找的是将此样式应用于正文的子级,因此请在选择器中添加一个空格body :not(.not-red)

body :not(.not-red) {
/*  ^ note the space here */
  color: #ff0000;
}
Run Code Online (Sandbox Code Playgroud)
<h1>This is a heading</h1>

<p class="not-red">This is a paragraph.</p>
<p class="not-red">This is another paragraph.</p>

<div>This is some text in a div element.</div>
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以覆盖样式,因为样式表将从上到下“读取”。

body {
  color: #ff0000;
}
.not-red {
  color: black;
}
Run Code Online (Sandbox Code Playgroud)
<h1>This is a heading</h1>

<p class="not-red">This is a paragraph.</p>
<p class="not-red">This is another paragraph.</p>

<div>This is some text in a div element.</div>
Run Code Online (Sandbox Code Playgroud)