1

So I got into a problem, I tried the following code in HTML and CSS:

//HTML

<div>
    <div class="sibling-hover">hover over me</div>
</div>

<div class="parent">
    <div>should disappear</div>
</div>
//CSS

.sibling-hover:hover .parent {
    display:none;
}

When I hover over the "sibling-hover" child, the "parent" div should disappear. It doesn't seem to work and I don't have any idea why.

I tried .sibling-hover:hover ~ .parent, .sibling-hover:hover + .parent and .sibling-hover:hover > .parent and none of them seem to work. Is there any reason I can't do it, and if so, can I do it in JavaScript instead?

aneesa
  • 11
  • 1
  • Thanks for whoever marked this as a duplicate, you didn't help at all. I already saw those questions and answers. – aneesa Jul 15 '21 at 19:40

1 Answers1

0

Actually what you wrote isn't right ... for ~ ( sibling ) selector to work you need to have siblings under a parent element take the below example.

HTML

<div> <!-- I am parent div -->
  
  <div class="sibling-hover"> 
    hover over me
  </div>

  <div class="parent">
    should disappear
  </div>
  
</div>

CSS

  .sibling-hover:hover ~ .parent {
    display: none;
  }

Also the css you wrote is correct in case if your markup is somewhat like this..

HTML

  <div><!-- Here i am parent -->
    <div class="sibling-hover"><!-- i am under parent -->
      hover over me
      <div class="parent"><!-- i am under sibling-hover ( i.e. sibling-hover is my parent element ) -->
        should disappear
      </div>
    </div>
  </div>

CSS

  /* when we hover over sibling-hover element the div with class .parent is affected with ! 
   Note only the element ( with parent class ) inside the . sibling-hover can make some affect to it 
 */
  .sibling-hover:hover .parent {
    display: none;
  }
Sanmeet
  • 1,191
  • 1
  • 7
  • 15