Thoughts about React,Web Development,Performance

May 5, 2021

General Sibling Combinator (~) in CSS

Giovanni Benussi
@giovannibenussi

What's the General Sibling Combinator?

  General Sibling Combinator

According to MDN:

The general sibling combinator (~) separates two selectors and matches all iterations of the second element, that are following the first element (though not necessarily immediately), and are children of the same parent element.

In other words, it matches all elements that follows a certain element as long as they share the same parent.

Let's see an example of this:

p {
  background-color: lightblue;
}

h1 ~ p {
  background-color: lightgreen;
}

The previous CSS with this markup:

<p>Before header 1</p>
<p>Before header 2</p>
<h1>Header</h1>
<p>After header 1</p>
<p>After header 2</p>

Will produce the following output:

Before header 1

Before header 2

Header

After header 1

After header 2

This selector only matches direct childrens. Keeping the same previous CSS but changing the markup to this:

<p>Before header 1</p>
<p>Before header 2</p>
<h1 className="font-bold text-xl">Header</h1>
<p>After header 1</p>
<p>After header 2</p>
<div>
  <p>Nested paragraph</p>
</div>

Produces the following output:

Before header 1

Before header 2

Header

After header 1

After header 2

Nested paragraph

Conclusion

The general sibling combinator gives us a convenient and precise way to match elements. Now that you have it in your toolbelt, be aware of opportunities to use it and let me know how it goes!

Do you have any question? Reach me out on message me on Twitter whenever you want.