CSS :has() pseudo class
Julia 👩🏻‍💻 GDE

Julia 👩🏻‍💻 GDE @yuridevat

About: 👋 Selftaught Accessibility & Frontend Developer 💻 Dev & UX Accessibility Specialist @Atos | CPACC 🙆 Improving the world with accessible web content ✍️ Content creator, Tips on How To Get Into Tech

Location:
Vienna, Austria
Joined:
May 11, 2020

CSS :has() pseudo class

Publish Date: Jan 4 '24
46 4

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;
}
Enter fullscreen mode Exit fullscreen mode

See the affect directly in Codepen

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

Comments 4 total

  • Jake Lundberg
    Jake LundbergJan 6, 2024

    So excited we can finally start using this!!! 🤗🎉😍

  • LopCuns
    LopCunsJan 6, 2024

    I had no idea about this css feature.It looks like it will afford us a bit of javascript code in our applications,so it is a great new.

  • Michael Pollaci
    Michael PollaciJan 9, 2024

    one word... YAY!

Add comment