In web development, it's often necessary to apply specific styling to elements based on their relationship with other elements in the DOM. One particular challenge is styling parent elements if they contain child elements.
Consider the following HTML structure:
<ul class="main"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li> <ul class="sub"> <li>Sub Item 1</li> <li> <ul> <li>Sub Sub Item 1</li> <li>Sub Sub Item 2</li> <li>Sub Sub Item 3</li> </ul> </li> <li>Sub Item 3</li> <li>Sub Item 4</li> <li>Sub Item 5</li> </ul> </li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> </ul>
To style in CSS the
ul li:has(ul.sub) { background-color: yellow; border: 1px solid black; }
By applying the background-color and border properties to li elements that meet the :has(ul.sub) condition, you can differentiate them from li elements that do not have any child ul.sub elements.
It's important to note that the :has() selector is not supported in all browsers, so using this approach may require browser compatibility considerations.
The above is the detailed content of How to Style a Parent Element Based on its Child Elements with CSS?. For more information, please follow other related articles on the PHP Chinese website!