具有 class .a 和 class .b 的元素的 CSS 选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/807415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:33:48  来源:igfitidea点击:

CSS selector for an element having class .a and class .b

csscss-selectors

提问by Raanan Avidor

I need to style an element that has both class .aand class .b. How do I do it?

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

The order the classes appear in the HTML might vary.

类在 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>

回答by bdukes

That's entirely possible. If you specify two classes on an element (without any spaces), that means that it must have both for the rule to apply.

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

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>

回答by Rob Kennedy

Class selectors can be combined:

类选择器可以组合:

div.a.b {
  color: red;
}

Quoting from the spec:

引用规范

To match a subset of "class" values, each value must be preceded by a ".".

For example, the following rule matches any P element whose "class" attribute has been assigned a list of space-separated values that includes "pastoral" and "marine":

p.marine.pastoral { color: green }

This rule matches when class="pastoral blue aqua marine"but does not match for class="pastoral blue".

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

例如,以下规则匹配其“class”属性已分配有空格分隔值列表的任何 P 元素,其中包括“pastoral”和“marine”:

p.marine.pastoral { color: green }

此规则匹配 whenclass="pastoral blue aqua marine"但不匹配 for class="pastoral blue"

回答by Claudio

div[class~="a"][class~="b"]{
color:#f00;
}

回答by Shoeb Ansari

/* select div tag having class a and b together */

/* 选择具有类 a 和 b 的 div 标签 */

 <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>

回答by cyborg_ar

Yeah, use a common class, or why not, JavaScript if the content changes dynamically

是的,如果内容动态更改,请使用公共类,或者为什么不使用 JavaScript