skip to Main Content

I need to create a animation with the fallowing steps:

  1. Initial: elementA with opacity 0;
  2. Once hover elementA‘s container (let’s call it containerA):
    • elementA translate from (-5px, 5px) to (0px, 0px);
    • elementA change opacity from 0 to 1;
    • animation duration: 0.5s;
  3. Once mouse leave containerA:
    • elementA change opacity from 1 to 0;
    • elementA doesn’t change translate position;
    • animation duration: 0.5s;

I’ve achieved this effect by adding/removing CSS class, you can see the here (https://jsbin.com/buqexadiru/edit?html,css,js,console,output)

My question is, how can I achieve this effect with pure CSS, without the add/remove class step; Is this possible?

2

Answers


  1. Use a transition for the opacity and an animation for the transform when the container is hovered.

    .container {
      margin: 1em;
      border: 2px solid blue;
      background: lightblue;
      width: 50vh;
      aspect-ratio: 1;
    }
    
    .item {
      width: 20vh;
      aspect-ratio: 1;
      background: green;
      opacity: 0;
      transform: translate(0%, 0%);
      transition: opacity .5s;
    }
    
    .container:hover .item {
      opacity: 1;
      animation-name: appear;
      animation-duration: .5s;
      animation-fill-mode: forwards;
    }
    
    @keyframes appear {
      0% {
        transform: translate(-50%, -50%);
      }
      100% {
        transform: translate(0%, 0%);
      }
    }
    <div class="container">
      <div class="item"></div>
    </div>
    Login or Signup to reply.
  2. Consider different transitions

    .container {
      margin: 1em;
      border: 2px solid blue;
      background: lightblue;
      width: 50vh;
      aspect-ratio: 1;
    }
    
    .item {
      width: 20vh;
      aspect-ratio: 1;
      background: green;
      opacity: 0;
      transform: translate(-50%, -50%);
      transition: opacity .5s,transform 0s .5s; /* on mouset out, wait until opacity is done to change transform */
    }
    
    .container:hover .item {
      opacity: 1;
      transform: translate(0%, 0%);
      transition: .5s; /* on hover transition both */
    }
    <div class="container">
      <div class="item"></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search