Search code examples
htmlcsscss-selectorsmousehover

How to chage CSS attributes of a Div when another Div is hovered that is located after the first Div


I have DIV 1 and DIV 2. In the code Div 2 is located after Div 1. I want to change the background colour of Div 1 when Div 2 is hovered. Preferebly I do not want to change the HTML structure and do not want to use JS.

div {
  background-color: yellow;
  padding: 20px;
  display: none;
}
  
span:hover div {
  display: block;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div>I will show on hover</div>
<span>Hover over me!</span>


</body>
</html>

Thanks in advance.


Solution

  • You can do what you want if you change the order in which the div and span are generated. If you don't want to change the order of elements it isn't possible without JS.

    div {
      background-color: yellow;
      padding: 20px;
      display: none;
    }
      
    span:hover + div {
      display: block;
    }
    <span>Hover over me!</span>
    <div>I will show on hover</div>