Ada*_*dam 437 css css-selectors
有没有办法根据设置为两个特定类的类属性的值来选择具有CSS的元素.例如,假设我有3个div:
<div class="foo">Hello Foo</div>
<div class="foo bar">Hello World</div>
<div class="bar">Hello Bar</div>
Run Code Online (Sandbox Code Playgroud)
我可以写什么CSS来选择列表中的第二个元素,基于它是foo和bar类的成员这一事实?
Bol*_*ock 693
链接两个类选择器(中间没有空格):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
Run Code Online (Sandbox Code Playgroud)
如果您仍然需要处理像IE6这样的古老浏览器,请注意它不能正确读取链式类选择器:它只会读取最后一个类选择器(.bar在本例中),而不管您列出的其他类.
为了说明其他浏览器和IE6如何解释这一点,请考虑这个CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Run Code Online (Sandbox Code Playgroud)
支持的浏览器上的输出是:
<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] -->
Run Code Online (Sandbox Code Playgroud)
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] -->
Run Code Online (Sandbox Code Playgroud)
脚注:
foo.foo和bar.bar.
bar.bar,不管列出的任何其他类.使用SASS:
.foo {
/* Styles with class "foo" */
&.bar {
/* Styles with class "foo bar" */
}
}
Run Code Online (Sandbox Code Playgroud)