skip to Main Content

I have these 2 divs and I want to make it so if you hover over "square", "square2"’s color changes. How do i do this? Preferably in css, but js is also possible.

hover over square 1 –> square 2 is now red instead of green

square:hover {
  #square2.background_color: #ff0000;
}
<div class="square">
  <p class="square1_text">~66.6%</p>
</div>

<div class="square2">
  <p class="square2_text">~33.3%</p>
</div>

4

Answers


  1. You can use the next-sibling combinator (+).

    .square:hover + .square2 {
      background-color: #ff0000;
    }
    <div class="square">
      <p class="square1_text">~66.6%</p>
    </div>
    <div class="square2">
      <p class="square2_text">~33.3%</p>
    </div>
    <button class="button"></button>
    Login or Signup to reply.
  2. .square:hover + .square2 {
      background-color: #ff0000;
    }
    <div class="square">
      <p class="square1_text">~66.6%</p>
    </div>
    <div class="square2">
      <p class="square2_text">~33.3%</p>
    </div>
    <button class="button"></button>
    Login or Signup to reply.
  3. In CSS, there is no combinator for selecting a previous sibling. So, you can use JavaScript if you want both divs to highlight the other on hover:

    const sq = document.querySelector('.square');
    const sq2 = document.querySelector('.square2');
    const squares = [sq, sq2];
    
    squares.forEach(function(square, i) {
      square.addEventListener('mouseover', function() {
        squares[Math.abs(i - 1)].style.backgroundColor = '#ff0000';
      });
      square.addEventListener('mouseout', function() {
        squares[Math.abs(i - 1)].style.backgroundColor = '#fff';
      });
    });
    <body>
      <div class="square">
        <p class="square1_text">~66.6%</p>
      </div>
      <div class="square2">
        <p class="square2_text">~33.3%</p>
      </div>
      <button class="button"></button>
    </body>
    Login or Signup to reply.
  4. Certainly! To achieve the desired effect where hovering over the first square (square) changes the background color of the second square (square2), you can use CSS. Here’s how you can modify your CSS:

     /* Apply styles when hovering over the first square */
    .square:hover + .square2 {
      background-color: #ff0000; /* Change this to your desired color */
    }
    

    The + selector targets the adjacent sibling element. In this case, it selects .square2 when .square is hovered.
    Adjust the background-color property to the color you want for the second square.
    Make sure to include this CSS in your stylesheet, and it should work as expected! 😊

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search