Ask any question about CSS here... and get an instant response.
Post this Question & Answer:
How can I use the :has() selector to style a parent element if it contains a specific child element in CSS? Pending Review
Asked on Dec 29, 2025
Answer
The `:has()` selector in CSS allows you to style a parent element based on the presence of a specific child element. This is a powerful feature that can help you create dynamic styles without JavaScript.
<!-- BEGIN COPY / PASTE -->
<style>
/* Style a parent div if it contains a child element with class 'highlight' */
div:has(.highlight) {
border: 2px solid blue;
background-color: lightyellow;
}
</style>
<div>
<p>This paragraph is not highlighted.</p>
</div>
<div>
<p class="highlight">This paragraph is highlighted, so the parent div is styled.</p>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- The `:has()` selector is part of the CSS Selectors Level 4 specification.
- It is not yet widely supported in all browsers, so check compatibility before using it in production.
- The example shows how a parent `div` is styled when it contains a child element with the class `highlight`.
- This selector can be useful for creating styles that depend on the presence of specific child elements.
Recommended Links:
