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 š¤©.
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
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
Top comments (4)
one word... YAY!
So excited we can finally start using this!!! š¤šš
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.
Exactly! Glad, you learned something from my article.