适用于具有两个类的元素的 CSS 选择器 [英] CSS Selector that applies to elements with two classes
问题描述
有没有办法根据设置为两个特定类的 class 属性的值来选择带有 CSS 的元素.例如,假设我有 3 个 div:
Hello Foo<div class="foo bar">Hello World</div><div class="bar">Hello Bar</div>
基于它是 foo 和 bar 类的成员这一事实,我可以编写什么 CSS 来仅选择列表中的第二个元素?
链接两个类选择器(中间没有空格):
.foo.bar {/* 带有 foo 和 bar 类的元素的样式 */}
<小时>
如果您仍然需要处理像 IE6 这样的古老浏览器,请注意它不会正确读取链式类选择器:它只会读取 last 类选择器 (.bar
在这种情况下),而不管您列出了哪些其他类.
为了说明其他浏览器和 IE6 如何解释这一点,请考虑以下 CSS:
* {颜色:黑色;}.foo.bar {红色;}
支持的浏览器上的输出是:
Hello Foo<!-- 未选中,黑色文本 [1] --><div class="foo bar">Hello World</div><!-- 选中,红色文本 [2] --><div class="bar">Hello Bar</div><!-- 未选中,黑色文本 [3] -->
在 IE6 上的输出是:
Hello Foo<!-- 未选中,黑色文本 [1] --><div class="foo bar">Hello World</div><!-- 选中,红色文本 [2] --><div class="bar">Hello Bar</div><!-- 选中,红色文本 [2] -->
脚注:
- 支持的浏览器:
- 未选中,因为该元素只有
foo
类. - Selected 因为此元素同时具有
foo
和bar
类. - 未选中,因为该元素只有
bar
类.
- 未选中,因为该元素只有
- IE6:
- 未选中,因为该元素没有
bar
类. - 已选择,因为此元素具有
bar
类,而不管列出的任何其他类.
- 未选中,因为该元素没有
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>
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 */
}
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.
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] -->
Output on IE6 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> <!-- Selected, red text [2] -->
Footnotes:
- Supported browsers:
- 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
.
- Not selected as this element only has class
- IE6:
- Not selected as this element doesn't have class
bar
. - Selected as this element has class
bar
, regardless of any other classes listed.
- Not selected as this element doesn't have class
这篇关于适用于具有两个类的元素的 CSS 选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!