DEV Community

loading...
Cover image for CSS - What does the tilde(~) mean?

CSS - What does the tilde(~) mean?

paulryan7 profile image Paul Ryan ・2 min read

I was recently asked what does the tilde symbol mean in CSS, I am a little embarrassed to say as a UI developer that I had no idea. Yikes!

Turns out it is actually quite simple and hopefully this post will clear up any confusion you may have in the next couple of minutes.

Take the following HTML and CSS.

<div class="b"></div>
<div class="a"></div>
<div class="b"></div>
<div class="b"></div>
<div class="c"></div>
div
  height: 100px
  width: 100px
  border: 1px solid red
  margin: 10px

This will give you the following visually:
Image of HTML

Now let's get to using our tilde symbol which is also known as a Subsequent-sibling Combinator. This basically means that it will select all siblings after a selector.

In our case, we want to set the background color of the 3rd and 4th element with the class of b to red. Yes, we could do this with nth-child but it is not as clean as using the tilde symbol.

We'll add the following CSS:

.a ~ .b
  background: red

This will select the two b classes after the a class which will give us the following.
Two squares with red background

Believe or not that is all there really is to the tilde symbol.

Here is the link to the pen.

Hope you learned something :)


I hope you enjoyed this post and it made things clearer for you. I often post what I am working on and content I am producing on my Instagram so be sure to give me a follow. I am trying to post more tech content on Instagram, anyone else fed up with pictures of the gym and food?

Discussion (0)

Forem Open with the Forem app