Targeting Elements with Multiple Classes Using CSS Selectors
When working with HTML and CSS, you may encounter situations where you need to select elements based on the values of specific classes. One common requirement is to select elements with multiple classes assigned to them.
Question:
Given three divs with the following classes:
<div class="foo">Hello Foo</div> <div class="foo bar">Hello World</div> <div class="bar">Hello Bar</div>
How can you write CSS to select only the second element (with the "foo bar" classes) using CSS selectors?
Answer:
To select elements with multiple classes, simply chain the class selectors without any space in between. In this example, the CSS code would be:
.foo.bar { /* Styles for element(s) with foo AND bar classes */ }
This selector will apply styles to the second div, as it is the only element that has both the "foo" and "bar" classes assigned to it.
Additional Note:
Older browsers like Internet Explorer 6 may not correctly interpret chained class selectors. IE6 will only read the last class selector and ignore the others. To ensure compatibility with IE6, you should avoid using chained class selectors and instead use more specific selectors, such as:
div.foo.bar { /* Styles for element(s) with foo AND bar classes */ }
The above is the detailed content of How Can I Select an HTML Element with Multiple Classes Using CSS Selectors?. For more information, please follow other related articles on the PHP Chinese website!