Skip to content
All posts
  • #css
  • #webdev
  • #frontend

CSS :has() pseudo class

Fortunately, the CSS :has() pseudo class is finally supported by all major browsers. Firefox took a...

Julia ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป GDEJulia ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป GDE2 min read46
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

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

Enjoyed this post?

Join the discussion on dev.to (4 comments) or share it.

Keep reading

4 min read

Red Team vs Blue Team โ€” I Choose You!

Itโ€™s 1999. You slide a Pokรฉmon Red Version cartridge into your Game Boy. Four AA batteries, a...

  • #cybersecurity
  • #programming
  • #webdev
Read