in ,

The Difference Between the Plus Sign (+) and Tilde (~) in CSS

CSS Selectors ~ +

The ~ and + are both sibling selectors in CSS. That means they apply the style to elements that share the same parent.

The difference is that the ~ selector selects *all* matching sibling elements, but the + selector selects only the *first* matching sibling element.

Time for some quick examples.

Let’s say your html looks like this:

<div>this is the div</div>
<p>paragraph one</p>
<p>paragraph two</p>

If this is your rule:

div ~ p{
  color: red;
}

Both “paragraph one” and “paragraph two” will be red.

However, if this is your rule:

div + p {
  color: red;
}

Only “paragraph one” will be red.

The only other thing to remember is these selectors only work on siblings *below* the first element in your rule. That might sound confusing, but it just means that if this is your html:

<p>paragraph zero</p>
<div>this is the div</div>
<p>paragraph one</p>
<p>paragraph two</p>

and we use either of the rules above, paragraph zero will never be red because it’s *above* the div.

If you like this content, check out my YouTube channel Terrible Whiteboard at https://www.youtube.com/channel/UCpLC2ohmappF2iUsWYRnsxg. I post answers to algorithm questions multiple times a week. This will help you in your job search since most coding jobs will give you at least one algorithm question in your interviews.

This post was created with our nice and easy submission form. Create your post!

What do you think?

Written by Terrible Whiteboard

If you like this content, check out my YouTube channel Terrible Whiteboard at https://www.youtube.com/channel/UCpLC2ohmappF2iUsWYRnsxg. I post answers to algorithm questions and web development tips and tricks multiple times a week.

Why WordPress Is Still The Best Content Management System

Javascript Sleep