skip to Main Content

I have a div and some component state representing whether or not that div is opened or closed.

When the state is !open, the component is hidden by display: none

When state changes to open, the component is now shown by changing to display: block

I slide the element into the screen. I do that through a keyframe animation.

@keyframes slide-in {
    0% {
        left: -100vw;
    }
    100% {
        left: 0;
    }
}
<div style={{ animation: slide-in 1s, display: open ? 'block' : 'none', position: 'absolute'}}>
   This slides open when state is changed to open.
</div>

This works great when I’m going from closed -> open. However, there’s no animation at all for when I go from open -> closed. Which is slightly jarring. I tried but could not find a simple way to do this – so many ridiculous answers with hacky visibility changes or JS event listeners and class name changing.

I find it impossible to believe there’s a very simple way to go one direction, but not the other, when usually you want both.

Any help on this would be greatly appreciated!!

2

Answers


  1. How about setting the position not using the absolute left and right value, but using transition? It’s more advisable to use css transition when applying an animation

    Login or Signup to reply.
  2. You can play an animation in reverse by setting animation-direction, but it seems more like you want a transition?

    .slide-open {
      transition: left 1s;
      left: -100vw;
    }
    
    .slide-open.open {
      left: 0;
    }
    
    <div className=`slide-open ${open ? 'open' : ''}`>
       This slides open when state is changed to open.
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search