Home >Web Front-end >CSS Tutorial >How Can I Style Parent Elements Based on Their Child Elements Using CSS?
Styling Parent Elements Based on Child Elements
It's possible to define CSS styles for an element that are applied based on the presence of specific child elements. This is achieved using the :has() pseudo-class.
Consider the following HTML:
<div> <div class="a"></div> </div> <div> <div class="b"></div> </div>
To style the parent div based on its children, use the :has() pseudo-class:
div:has(div.a) { border: solid 3px red; } div:has(div.b) { border: solid 3px blue; }
The first div will have a red border because it contains a child div with class "a". The second div will have a blue border because it contains a child div with class "b".
Note: Prior to the :has() pseudo-class, this behavior could only be achieved using JavaScript.
The above is the detailed content of How Can I Style Parent Elements Based on Their Child Elements Using CSS?. For more information, please follow other related articles on the PHP Chinese website!