Giovanni Benussi

General Sibling Combinator (~) in CSS

Giovanni Benussi · 2 min read

What’s the 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 children. Keeping the same previous CSS but changing the markup to this:

<p>Before header 1</p>
<p>Before header 2</p>
<h1>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!