csscss-animations

How do I reuse keyframes to play an animation backwards?


I have the following css:

    @keyframes expandTop {
      from {
        height: 0;
      }
      to {
        height: 100px;
      }
    }
    &.expand {
      animation: expandTop 0.5s ease-out forwards;
    }
    @keyframes collapseTop {
      from {
        height: 100px;
      }
      to {
        height: 0;
      }
    }
    &.collapse {
      animation: collapseTop 0.5s ease-out forwards;
    }
    &.still {
      animation: none;
    }
  }

This works but it feels like there should be a way to reuse the same @keyframes. I tried a bunch of combinations of reverse and backwards etc.. but to no avail. The animation is triggered by switching css class. I'd like something along those lines but that works:

    @keyframes top {
      from {
        height: 0;
      }
      to {
        height: 100px;
      }
    }
    &.expand {
      animation: top 0.5s ease-out forwards;
    }
    &.collapse {
      animation: top 0.5s ease-out reverse backwards;
    }
    &.still {
      animation: none;
    }

I've been banging my head on the docs but that's not helping... Am I screwed because I am using classes to trigger?


Solution

  • This is a job for transition not for animation

    function e() {
      document.getElementById('div').classList.toggle('collapse');
      document.getElementById('div').classList.toggle('expand');
    }
    .still {
      transition: height 1s;
      background: red;
    }
    
    .collapse {
      height: 0;
    }
    
    .expand {
      height: 100px;
    }
    <button onclick="e()">switch</button>
    
    <div id="div" class="collapse still"></div>