Home >Web Front-end >CSS Tutorial >How Can I Target Elements with Multiple Classes Using CSS Selectors?
CSS Selectors for Elements with Multiple Classes
Determining ways to target elements with specific class combinations in CSS can be a common requirement in web development. Consider this scenario where three div elements have different class combinations:
<br><div><div class="foo bar">Hello World</div><br><div>
The task is to select the second element, which has both the foo and bar classes.
Solution: Chained Class Selectors
To achieve this, CSS selectors provide a straightforward solution: chaining class selectors. Simply write the class names together, without any spaces, as in this code:
.foo.bar { /* Styles for elements with both foo and bar classes */ }
This selector will only apply to the second div element in the provided HTML, as it is the only element that has both classes.
Caution for Internet Explorer 6
However, it's important to note that Internet Explorer 6 has a caveat when it comes to chained class selectors. It only recognizes the last class selector in the chain, ignoring any preceding ones. In the example above, IE6 will only apply the styles to elements with the bar class, not to elements that also have the foo class.
Example
Consider the following snippet:
*{ color:black; } .foo.bar { color:red; } <div>
In this scenario, non-IE6 browsers will apply the red color to the second div, while IE6 will apply it to the third div since it only considers the bar class. This behavior can be particularly important to be aware of if supporting older browsers is a requirement.
The above is the detailed content of How Can I Target Elements with Multiple Classes Using CSS Selectors?. For more information, please follow other related articles on the PHP Chinese website!