0

According to W3Schools:

  • div + p {} selects all <p> elements that are placed immediately after <div> elements

  • p ~ div selects every <div> element that is preceded by a <p> element

So what's the difference?

I am trying to make a <div id="bar"> appear when <div id="foo"> is on hover, and in my CSS both #foo:hover ~ #bar and #foo:hover + #bar seem to do the exact same thing.

Fiddle with ~ selector

Fiddle with + selector

#foo,
#bar {
  height: 200px;
  width: 200px;
}

#foo {
  background-color: indianred;
  cursor: pointer;
}

#bar {
  visibility: hidden;
  background-color: steelblue;
}

/* Example 1 */
#foo:hover ~ #bar {
  visibility: visible;
}
/* Example 2 */
#foo:hover + #bar {
  visibility: visible;
}
/* Both example 1 & 2 do the same thing */
<div id="foo">

</div>

<div id="bar">

</div>

1 Answers1

2

A simple demonstration of the difference

First +

Selects only the p immediately following the div

div+p {
  color: Red;
}
<div>
  SOME DIV
</div>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore unde ipsam iusto veniam, neque natus perferendis pariatur, ipsa doloremque odit atque sunt vitae. Tempore iste nesciunt sint assumenda accusamus dolorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae sint, ullam reiciendis officia placeat tenetur enim harum eos adipisci natus quis totam corrupti nostrum at sunt ipsam labore dolor voluptate.</p>

and ~ selects all p following the div.

div~p {
  color: red;
}
<div>
  SOME DIV
</div>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore unde ipsam iusto veniam, neque natus perferendis pariatur, ipsa doloremque odit atque sunt vitae. Tempore iste nesciunt sint assumenda accusamus dolorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae sint, ullam reiciendis officia placeat tenetur enim harum eos adipisci natus quis totam corrupti nostrum at sunt ipsam labore dolor voluptate.</p>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • I don't understand ... there is no explanation of the CSS selectors and how they work. –  Mar 08 '20 at 09:52
  • @TheStackOverflowCommunity the demo is self-explanatory, simply run it and you will understand. Sometimes words aren't needed to explain things. – Temani Afif Mar 08 '20 at 10:13