Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a CSS hover effect to an element that’s not a child of the hovered element

Tags:

html

css

hover

The tilde sign(~) only works on #header. But if I want to try it on li tag it's not working because it's inside of #header.

#header {
  background-color: red;
}
/*
    header:hover ~ .element {
     background-color:blue;
    }
    */

li:hover ~ .element {
  background-color: blue;
}
.element {
  background-color: green;
}
<header id="header">
  <li><a href="#">Hover</a>
  </li>
</header>

<div class="element">
  <p>hello world</p>
</div>
like image 638
Abdul Rehman Avatar asked Dec 31 '25 09:12

Abdul Rehman


1 Answers

Do like this:

#header {
      background-color: red;
    }
    /*
    header:hover ~ .element {
    background-color:blue;
    }
    */

    #header:hover ~ .element {
      background-color: blue;
    }
    .element {
      background-color: green;
    }
<header id="header">
      <li><a href="#">Hover</a>
      </li>
    </header>

    <div class="element">
      <p>hello world</p>
    </div>

You have all your li elements inside the #header. So, the div with class="element" will always be placed after the header. There is no need to select the li:hover

like image 85
RafaelTSCS Avatar answered Jan 02 '26 22:01

RafaelTSCS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!