skip to Main Content

I’d like my div to move when hovering an existing div

.divToMove {
    transform: translateY(-100%);
}

@keyframes slideIn {
    from {
        transform: translateY(-100%);
    }
    to {
        transform: translateY(-35%);
    }
}

.divToHover:hover .divToMove {
    animation: slideIn 0.5s forwards;
}

the div is "stuck" where it originally was placed, I’d like it to transition from -100% in Y to -35

2

Answers


  1. Adjacent sibling combinator – + in CSS – MDN Docs

    The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element.

    /* only need the container for testing purposes, to position the two divs next to each other in the center of the screen */
    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    
    .divToHover {
      width: 200px;
      height: 200px;
      background-color: lightblue;
      text-align: center;
      line-height: 200px;
    }
    
    .divToHover:hover {
      background-color: lightgreen;
    }
    
    .divToMove {
      width: 100px;
      height: 100px;
      background-color: pink;
      transition: transform 0.5s;
    }
    
    /* when I hover over the .divToHover class, add the styles of the .divToMove class */
    .divToHover:hover + .divToMove {
      transform: translateY(-35%);
    }
    <div class="container">
      <!-- Hover -->
      <div class="divToHover">
        Hover me!
      </div>
      <!-- Moved -->
      <div class="divToMove">
        Moving Div
      </div>
    </div>
    Login or Signup to reply.
  2. You can’t directly modify other element’s styling on hover. You need to make use of CSS Combinators

    Here, I have used General Sibling Selector (~), which selects all .divToMove elements that are next siblings of .divToHover.

    If .divToMove and .divToHover remain adjacent, you can also use the + combinator.

    .divToMove {
        margin-top: 100px;
        transform: translateY(-100%);
    }
    
    @keyframes slideIn {
        from {
            transform: translateY(-100%);
        }
        to {
            transform: translateY(-35%);
        }
    }
    
    .divToHover:hover ~ .divToMove {
        animation: slideIn 0.5s forwards;
    }
    <div class="divToHover">HOVER</div>
    <div class="divToMove">MOVE</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search