【问题标题】:CSS use :not ID with CLASSCSS 使用 :not ID with CLASS
【发布时间】:2017-02-13 12:17:35
【问题描述】:

有人知道如何将 CSS 选择器 :not() 用作 #some_id:not(.any_class_name) 吗?

代码看起来好像是正确的,但它不起作用。没有not 选择器还有其他方法吗?我在互联网上找不到任何东西。

我正在制作一个 Web 应用程序,其中包含多个页面,但有几个页面包含带有 id=some_id 的 div。我以为我必须通过添加 any_class_name 一次来添加特定的 CSS 使用上面的 CSS 代码解决问题,但它不起作用。

【问题讨论】:

  • 你能提供一个选择器不工作的例子吗?如果你也创建一个 JSFiddle 会更好。
  • Id 的每页应该只出现 一次。共享相同 ID 的多个元素会导致 HTML 无效。
  • @SecretSquirrel 最好避免 w3schools 引用,最好使用developer.mozilla.org/en-US/docs/Web/CSS/:not
  • @JustusRomijn 具有唯一 ID 的唯一元素可能具有也可能没有给定的 CSS 类(例如 #secondMenuItem.selected、#inputPassword.error)——问题与唯一 ID 不矛盾原则。

标签: css css-selectors


【解决方案1】:

我相信您正在颠倒选择器。您有一些具有相同class 的元素,但您想过滤掉具有特定ID 的元素。在这种情况下:

HTML:

<p class="someclass">hello</p> <!-- will be targeted by css below, thus green -->
<p class="someclass" id="some-id">hi</p> <!-- will not be targeted by css below -->

CSS:

.someclass:not(#some-id){ color: green; } 
/* selects all elements with classname 'someclass', 
   but excludes the one that has also has an id of 'some-id' */

正如@secretSquirrel 指出的那样,请注意browser compatibility:Internet Explorer 8 及更早版本不支持此选择器。

【讨论】:

  • 这个问题在哪里暗示存在多个具有相同 ID 的元素?
  • 我们怎样才能多次使用id?
  • @BoltClock'saUnicorn ow,我想因为 OP 询问了一个过滤 id 选择器的示例,同一页面上必须有多个元素共享一个 id,因为你为什么需要 @ 987654326@选择器是否只选择了一个元素?
  • @BoltClock'saUnicorn 我误读了 OP,我已经更新了我的答案。感谢您的评论。
【解决方案2】:

这将设置除&lt;a&gt;&lt;/a&gt;之外的所有背景:

:not(a)
{
     background: gray;
}

【讨论】:

    【解决方案3】:

    希望对你有帮助。

    Demo

    另一种方法是: 您可以覆盖css。也许你想要这样的东西。

    <div id="demo">
    <p class="class">This is a paragraph.</p>
    <p>This is another paragraph.</p>
    </div>
    

    你的 CSS

    #demo
    {
    color:#0000ff;
    }
    .class
    {
    color:#ff0000;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 2021-04-17
      • 2020-12-03
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 2016-05-06
      相关资源
      最近更新 更多