CSS :has() pseudo class

Fortunately, the CSS :has() pseudo class is finally supported by all major browsers. Firefox took a while, but on December 19, 2023 it was finally ready 👏🏽👏🏽👏🏽.

The :has() pseudo class is very useful and opens up a lot of new possibilities. You can now finally style the parent if it contains certain children. It's a feature I've wanted since the beginning of my coding journey 🤩.

Browser support for :has() pseudo-class. All browser support it now.

Here is what the selector :has() to offer (pun ... 😏).

/* parent section has a specific element, ul */

section:has(ul) {
  background: red;
}

/* parent section both elements, h1 and ul */

section:has(h1):has(ul) {
  background: hotpink;
}

/* parent section has either or both elements, h2 and or p */

section:has(h2, p) {
  background: lightblue;
}

/* parent section does not have h3 element */

section:not(:has(h3)) {
  background: yellow;
}

/* h3 which is followed by a p */

h3:has(+ p) {
  background: limegreen;
}

/* section has an input that is checked, then the label gets bold */

section:has(input:checked) label {
  font-weight: 900;
}

section:has(> form) {
  background: unset;
  margin-top: 20px;
}

/* field validation: field has required attribute */

form:has(input:required) {
  border-left: 3px solid red;
  padding-left: 4px;
}

/* field validation: input is invalid */

form:has(input:invalid) label {
  color: red;
  font-weight: 900;
}

See the affect directly in Codepen

{% codepen https://codepen.io/YuriDevAT/pen/poYvGQr %}

What are you excited about to use the :has() pseudo-class for?

Share you code snippets in the comment section below 👇🏽


Read more about the :has() pseudo class on MDN https://developer.mozilla.org/en-US/docs/Web/CSS/:has