【问题标题】:CSS: Target an element that has none of a list of classesCSS:定位一个没有类列表的元素
【发布时间】:2020-01-10 00:25:35
【问题描述】:

我想为某些元素创建一个规则,该规则只影响一个元素,如果它有一个没有类列表。

我的尝试:

div:not(.a, .c) {
  color: red;
}
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>

如果你运行这个 sn-p,它显然不能按预期工作。似乎选择器无效并且不会影响任何div。

接下来我尝试链接:not(),这看起来很笨拙,但有效:

div:not(.a):not(.c) {
  color: red;
}
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>

这是解决给定问题的唯一方法吗?

【问题讨论】:

标签: css css-selectors


【解决方案1】:

在 CSS 中链接 :not() 选择器是目前(2020 年 1 月)指示逻辑 AND 运算符的唯一方法。

所以,是的:

div:not(.a):not(.c)

是正确的写法:

div:not(.a) 与 div:not(.c)

div:not(.a):not(.c) {
  color: red;
}
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>

【讨论】:

    【解决方案2】:

    我认为通过您的问题,您总是知道您不想更改样式的课程。所以假设这是我的看法。

    .all {
      /** give default styles to all elements */
      color: red;
    }
    
    .a,
    .c {
      /** then reset the ones you where targeting with :not():not()... */
      color: black;
    }
    <div class="all a">a</div>
    <div class="all b">b</div>
    <div class="all c">c</div>

    【讨论】:

    • 我怀疑这正是 OP 试图避免的。
    • 没错。我有一个更复杂的场景,我需要这个,并且想方设法避免特异性战争。
    猜你喜欢
    • 2014-02-12
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2013-03-17
    • 2015-05-13
    • 1970-01-01
    相关资源
    最近更新 更多