0

Given a basic menu and div like below..

#link:hover ~ #custom {
    background: #ccc
}
<div class="header">
  <div class="nav">
    <ul>
      <li>
        <a id="link" href="#">Link</a>
      </li>
    </ul>
  </div>
</div>

<div id="custom">
  Custom Content
</div>

I have tried using the general sibling combinator but it isn't working.

Is there a way using CSS that I can get the custom div to also change background color when the nav item is hovered?

Do I need Javascript or can this be achieved more simply?

jsmitter3
  • 411
  • 1
  • 4
  • 15
  • 1
    Refer this https://stackoverflow.com/questions/6910049/on-a-css-hover-event-can-i-change-another-divs-styling – chandan_kr_jha Mar 30 '21 at 10:11
  • I have tried using the adjacent sibling combinator but it isn't working. Have updated the op – jsmitter3 Mar 30 '21 at 10:12
  • 2
    Not by now. CSS can't select the parent node. You have to use JavaScript onmouseover/mouseout and add/remove a class from `div.custom`. check also [this answer](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – Christopher Mar 30 '21 at 10:13
  • With that html structure, you would need js. *I have tried using the adjacent sibling combinator* - `#link` has no siblings which is why that doesn't work – Pete Mar 30 '21 at 10:15

3 Answers3

-1

you can change mydiv css with hover mynav try this css.

<style>
#mynavid:hover +#mydivid{color:red;}
</style>
  • I think the point is there are going to be other links in the nav that show other divs too, plus with op's html structure, you would have to put the hover on the header, not the nav – Pete Mar 30 '21 at 10:18
-1

here is the simple code I hope this will help...

.card {
    width: 150px;
}

.image {
    height: 80px;
  background-color: tomato;
}

.description {
  height: 80px;
  background-color: limegreen;
}

.image:hover ~ .description .link,
.link:hover {
    color: #ff0;
    background-color: white;
    }
<div class="card">
  <div class="image">img</div>
  <div class="description">
    <a class="link" href=#>some link</a>
    <div class="text">Fulfilled direction use continual set.</div>
  </div>
</div>
Aahad
  • 507
  • 4
  • 13
-1

Yes you can do it using j-query. The below will be the script code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
      $(document).ready(function(){
    $(document).mousemove(function(){
         if($("#nav-link:hover").length != 0){
            $(".custom").css("background-color","red");
        } else{
          $(".custom").css("background-color","");
        }
      });
    });
    </script>
<div class="header">
  <div class="nav">
    <ul>
      <li>
        <a href="#" id="nav-link">Link</a>
      </li>
    </ul>
  </div>
</div>
<div class="custom">
  Custom Content
</div>

Add this code to your above code and it will work

Yash Renwa
  • 41
  • 3