【问题标题】:Exclude a class from all of the selectors in CSS从 CSS 中的所有选择器中排除一个类
【发布时间】:2021-07-31 00:28:03
【问题描述】:

首先对不起我的英语不好。 我想从 CSS 中的所有选择器中排除一个类。

我需要使用类似的东西

(h1, h2, h3, h4, ..., p, span, a, ...):not(.exclude){
   font-family: arial;
}

代替:

h1:not(.exclude), h2:not(.exclude), ..., a:not(.exclude){
   font-family: arial;
}

【问题讨论】:

  • 只需为.exclude 元素设置一个特定规则,该规则将覆盖应用于所有元素的默认规则
  • 你不能单独使用 :not(.exclude) 有什么原因吗?您是否有任何特定的 .exclude 元素要从该规则中排除?

标签: html css css-selectors


【解决方案1】:

可以使用 CSS4 :is 选择器。您可以在此处注意浏览器支持:https://caniuse.com/?search=is,但在现代 Web 开发人员的术语中,您可以安全地使用它。

:is(h1,h2,h3):not(.exclude) {
  background: #bada55;
  color: #565656;
  padding: 10px;
}
<h1 class="exclude">
  Excluded
</h1>
<h2 class="include">
  Included
</h2>
<h3 class="exclude">
  Excluded
</h3>

上面的代码是这样工作的

h1:not(.exclude), h2:not(.exclude), h3:not(.exclude) { Properties... }

您也可以使用:where,它的作用相同:

:where(h1,h2,h3):not(.exclude) {
  background: #bada55;
  color: #565656;
  padding: 10px;
}
<h1 class="exclude">
  Excluded
</h1>
<h2 class="include">
  Included
</h2>
<h3 class="exclude">
  Excluded
</h3>

【讨论】:

    【解决方案2】:
    *:not(.exclude) {
      font-family: arial;
    }
    

    除了带有 .exclude 类的元素之外,所有字体系列都会使用 arial,但我不确定这是否是您的意思。

    【讨论】:

    • 列出他们想要应用的所有元素类型 :not(.exclude) 似乎表明存在他们不希望这种否定适用的元素类型。他们似乎更容易添加第二个 :not() 来排除元素类型的选择,而不是列出他们确实希望它适用的所有元素类型。但是,如果他们只想将这种否定应用于所有元素,那么这个答案就是要走的路。
    猜你喜欢
    • 2019-04-07
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多