CSS选择器,适用于具有两个类的元素 [英] CSS Selector that applies to elements with two classes
问题描述
有一种方法可以选择一个CSS元素,基于类属性的值设置为两个特定的类。例如,假设我有3个div:
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:
<div class="foo">Hello Foo</div>
<div class="foo bar">Hello World</div>
<div class="bar">Hello Bar</div>
我可以写什么CSS只选择列表中的第二个元素,基于它是
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?
推荐答案
链接两个类选择器(两者之间没有空格):
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
仍然需要处理像IE6这样的古老的浏览器,注意它没有正确读取链接类选择器:它只会读取最后类选择器( .bar <
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 last class selector (.bar
in this case) instead, regardless of what other classes you list.
为了说明其他浏览器和IE6如何解释这一点,考虑这个CSS:
To illustrate how other browsers and IE6 interpret this, consider this 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] -->
在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] -->
脚注:
- 支持的浏览器:
- Supported browsers:
- 未选择,因为此元素只有类
foo
- 已选择,因为此元素同时具有
foo
和c。 。
- Not selected as this element only has class
foo
. - Selected as this element has both classes
foo
andbar
. - Not selected as this element only has class
bar
.
- 未选择,因为此元素没有类
bar
。 -
- Not selected as this element doesn't have class
bar
. - Selected as this element has class
bar
, regardless of any other classes listed.
bar
b $ b
这篇关于CSS选择器,适用于具有两个类的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!