适用于具有两个类的元素的 CSS 选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3772290/
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
CSS Selector that applies to elements with two classes
提问by Adam
Is there a way to select an element with CSS based on the value of the class attribute being set to two specific classes. For example, let's say I have 3 divs:
有没有办法根据设置为两个特定类的 class 属性的值来选择带有 CSS 的元素。例如,假设我有 3 个 div:
<div class="foo">Hello Foo</div>
<div class="foo bar">Hello World</div>
<div class="bar">Hello Bar</div>
What CSS could I write to select ONLY the second element in the list, based on the fact that it is a member of both the foo AND bar classes?
基于它是 foo 和 bar 类的成员这一事实,我可以编写什么 CSS 来仅选择列表中的第二个元素?
回答by BoltClock
Chain both class selectors (without a space in between):
链接两个类选择器(中间没有空格):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the lastclass selector (.bar
in this case) instead, regardless of what other classes you list.
如果您仍然需要处理像 IE6 这样的古老浏览器,请注意它不会正确读取链接的类选择器:它只会读取最后一个类选择器(.bar
在这种情况下),而不管您列出哪些其他类。
To illustrate how other browsers and IE6 interpret this, consider this CSS:
为了说明其他浏览器和 IE6 如何解释这一点,请考虑以下 CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
支持的浏览器上的输出是:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
IE6 上的输出是:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
脚注:
- Supported browsers:
- Not selectedas this element only has class
foo
. - Selectedas this element has both classes
foo
andbar
. - Not selectedas this element only has class
bar
.
- Not selectedas this element only has class
- IE6:
- Not selectedas this element doesn't have class
bar
. - Selectedas this element has class
bar
, regardless of any other classes listed.
- Not selectedas this element doesn't have class
- 支持的浏览器:
- 未选择,因为此元素只有 class
foo
。 - 选择作为此元素同时具有类
foo
和bar
. - 未选择,因为此元素只有 class
bar
。
- 未选择,因为此元素只有 class
- IE6:
- 未选择,因为此元素没有 class
bar
。 - 选择此元素具有 class
bar
,而不管列出的任何其他类。
- 未选择,因为此元素没有 class