:has() CSS Pseudo Class

Description

The CSS :has() pseudo-class is a powerful tool that allows developers to select elements based on their children. It can be used to style a parent element based on the presence or absence of certain child elements, or to style child elements based on the presence or absence of certain siblings.

The :has() pseudo-class takes a selector list as an argument, and selects the element if any of the selectors in the list match at least one of its child elements. For example, the following selector would select all <div> elements that contain an <img> child element:

div:has(img) {
/* CSS rules to style the `<div>` element */
}

The :has() pseudo-class can also be used to select elements based on the presence or absence of certain siblings. For example, the following selector would select all <p> elements that are immediately followed by an <img> element:
p:has(+ img) {
/* CSS rules to style the `<p>` element */
}

The :has() pseudo-class can be used in conjunction with other CSS selectors to create even more specific and dynamic styling. For example, the following selector would select all <div> elements that contain an <img> child element and are also hovered over:
div:has(img):hover {
/* CSS rules to style the `<div>` element when it is hovered over */
}

The :has() pseudo-class is a powerful tool that can be used to create more complex and dynamic CSS styling. It is especially useful for styling forms, menus, and other interactive elements.

Syntax

:has(<relative-selector-list>) {
  /* ... */
}

Example

<section>
<article>
<h1>Morning Times</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</p>
</article>
<article>
<h1>Morning Times</h1>
<h2>Delivering you news every morning</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</p>
</article>
</section>
section {
display: flex;
align-items: start;
justify-content: space-around;
}

article {
display: inline-block;
width: 40%;
}

h1,
h2 {
font-size: 1.2em;
}

h2 {
font-size: 1em;
color: rgb(150, 149, 149);
}

h1,
h2 {
margin: 0 0 1rem 0;
}

h1:has(+ h2) {
margin: 0 0 0.25rem 0;
}

Browser Support

The following table will show you the current browser support for the CSS :has() pseudo class.

Desktop
Edge Chrome Firefox Opera Safari
1051051039115.4
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
105x7215.420105

Last updated by CSSPortal on: 1st October 2023