I was listening to the Syntax podcast and they threw out the question
What is the difference between the + and ~ selectors.
Hmmmm, the ~ selector..... what did that do again? So decided to test a few selectors out.
I'm going to go over these css statements
- div > p
- div + p
- div ~ p
- div p
The > selector
First up, div > p
. This selects any paragraph tag that is a direct child of a div tag.
<div>
<p>I am a child of a div</p>
</div>
The + selector
Next up, div + p
. This selects any paragraph tag that immediately follows a div tag.
<div>some great content</div>
<p>I am right after the div</p>
The ~ selector
Now we get to the selector that prompted this whole exercise, div ~ p
. Ok, turns out this selects <p> tags that follow a div, but not necessarily the immediately follow.
<div>more great content</div>
<p>I'm after the div</p>
<p>Hey, so am I :)</p>
Last up, div p
. This selects any <p> tags that have a <div> as a ancestor element, but it doesn't matter if it is a direct parent or not.
<div>
<ul>
<li><p>I see you div</p></li>
</ul>
</div>
And here's a pen showing them in action. And yes, I am available for freelance design gigs :)