【问题标题】:CSS selector for an element having class .a and class .b具有类 .a 和类 .b 的元素的 CSS 选择器
【发布时间】:2020-08-05 05:17:53
【问题描述】:

我需要为一个同时具有.a 类和.b 类的元素设置样式。我该怎么做?

类在 HTML 中出现的顺序可能会有所不同。

<style>
    div.a ? div.b {
        color:#f00;
    }
</style>
<div class="a">text not red</div>
<div class="b">text not red</div>
<div class="a b">red text</div>
<div class="b a">red text</div>

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    这完全有可能。如果您在一个元素上指定两个类(没有任何空格),这意味着它必须同时具有这两个类才能应用规则。

    div.a {
      color: blue;
    }
    div.b {
      color: green;
    }
    div.a.b {
      color: red;
    }
    <div class="a">
      A
    </div>
    <div class="b">
      B
    </div>
    <div class="a b">
      AB
    </div>

    【讨论】:

    • IE9 支持这个吗?我遇到的问题是只有一个类的元素正在采用这种样式。这是我正在使用的文档类型.. ttp://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" rel="nofollow" target="_blank">w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    • @Dib,我在 JS Bin (jsbin.com/xepemipuqo/1/edit) 上使用该文档类型创建了一个示例,该示例在 IE 9 中运行良好。希望对您有所帮助!
    【解决方案2】:

    可以组合类选择器:

    div.a.b {
      color: red;
    }
    

    引用the spec:

    要匹配“类”值的子集,每个值必须以“.”开头。

    例如,以下规则匹配任何 P 元素,其“类”属性已被分配了一个空格分隔值列表,其中包括“田园”和“海洋”:

    p.marine.pastoral { color: green }
    

    此规则在 class="pastoral blue aqua marine" 时匹配,但在 class="pastoral blue" 时不匹配。

    【讨论】:

      【解决方案3】:
      div[class~="a"][class~="b"] {
          color: #f00;
      }
      

      【讨论】:

      • 我喜欢这个,但值得一提的是,对旧版浏览器的支持相当低。
      【解决方案4】:
      /* select div tag having class a and b together */
      <style>
      div.a.b
      { 
          color:#f00;
      }
      </style>
      <div class="a">text not red</div>
      <div class="b">text not red</div>
      <div class="a b">red text</div>
      <div class="b a">red text</div>
      

      【讨论】:

        【解决方案5】:

        是的,如果内容动态变化,请使用通用类,或者为什么不使用 JavaScript

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-07
          • 1970-01-01
          • 2012-08-16
          • 2023-03-09
          • 1970-01-01
          • 2011-02-12
          相关资源
          最近更新 更多