CSS - Using the :has() Pseudo-Class

CSS - Using the :has() Pseudo-Class

Styling based on siblings and children

NOTE: many of the examples below are shown using SCSS. We do this only for the convenience of nesting styles and could be represented in SCSS using the child "combinator" (less than symbol: <).

The Problem

Children Rule!!

One of the challenges of CSS is that it is easy to style a child element based on the parent.

scss
1article {
2  .heading { 
3    background: black; 
4    color: white: 
5      text-align: center; 
6  }
7  .section { margin: 1rem 0; }
8  .resources { margin: 1rem 0; font-size: 0.8rem; }
9}

Here, we can easily style the various children of the articleelement. But what if we want to style an article with a heading different than an article without a heading?

Younger Siblings Always Get the Attention

CSS has the next-sibling "combinator" (+) which matches the second (younger) element. And we have the subsequent-sibling "combinator" (~), which matches all instances of the second element. Consider the style

scss
1span { color: green; }
2span + a { color: red; }
3span ~ abbr { color: goldenrod; }

And the HTML:

html
1<div>
2  <span>James</span>
3  <a href="#">Chester</a>
4  <abbr title="Theodore">Teddy</abbr>
5  <span>Woodrow</span>
6</div>

What is the output?

The output will be "James Chester Teddy Woodrow" but what color will the names will be in?

Select One

Want to explore Decendent and Sibling CSS selectors? Check out our Pen.

What About Parents?

How do we style a parent element that has a child with a specific trait? For example, how do we style an article that has a heading?

The Solution - :has()

CSS pseudo-class :has() allows us to style a parent based on some child trait.

scss
1.parent {
2  padding: 1rem;
3  background: gray;
4}
5.parent:has(.fancy) {
6  background: cornflowerblue;
7}
8.parent:has(> .fancy) {
9  background: lime;
10}

Here, an element with the class .parent will have a gray background. However, if the .parent element has a descendant element with the CSS class .fancy, the .parent element will have a cornflower blue background. If the .parent element has a direct descendant (child) element with the CSS class .fancy, the .parent element will have a lime background.

More Examples

Style Based on Siblings

In addition to being able to style a parent based on descendants, we can style an element based on their siblings.

Example Pen

Advanced Uses

I have only scratched the surface of the use of :has()selectors. I recommend reading the Google Developer Blog article on using :has()! Great for inspiration!

popularity
Electric
posted
Nov. 01, 2023