CSS Selector that applies to elements with two classes
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 开发者_StackOverflow中文版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 Internet Explorer 6, 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 snippet:
* {
color: black;
}
.foo.bar {
color: red;
}
<div class="foo">1. Hello Foo</div>
<div class="foo bar">2. Hello World</div>
<div class="bar">3. Hello Bar</div>
The page will look like this:
On 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
In Internet Explorer 6:
- Not selected as this element doesn't have class
bar
. - Selected as this element has class
bar
, regardless of any other classes listed. - Selected as this element has class
bar
.
- Not selected as this element doesn't have class
With SASS:
.foo {
/* Styles with class "foo" */
&.bar {
/* Styles with class "foo bar" */
}
}
See https://stackoverflow.com/a/49401539/7470360
精彩评论