Search code examples
htmlcsscss-animationstransition

How would I make a transition for the div to slide to the left and come out through the right side?


Hello I am trying to make a 'Sliding Pages animation', but it is just one page, or div. I want when I click a button. The div slides out of the page to the left, and comes out thorough the right.

For instance | Animation
| <--- Div <----- |


Solution

  • Here is a simple example where the div first slides out completely to the left and then comes in from the right.

    It uses CSS animation to do this, for the first half of the animation sliding it to the left and out of view and for the second half sliding it in from the right.

    Note, there is a little 'fiddle' at the half way point where we take the div from the left to the right, but with opacity very temporarily at 0. This is to prevent any possibility of a slight 'flash' as the div is moved across the screen.

    const div = document.querySelector('div');
    const button = document.querySelector('button');
    div.addEventListener('animationend', function() {
      div.classList.remove('move');
    });
    button.addEventListener('click', function() {
      div.classList.add('move');
    });
    * {
      margin: 0;
    }
    
    button {
      position: fixed;
      z-index: 1;
    }
    
    div {
      background-image: linear-gradient(to right, red, blue);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100vw;
      height: 100vh;
    }
    
    .move {
      animation-name: move;
      animation-duration: 2s;
      animation-iteration-count: 1;
      animation-fill-mode: forwards;
    }
    
    @keyframes move {
      0% {
        transform: translateX(0);
      }
      50% {
        transform: translateX(-100%);
        opacity: 1;
      }
      50.001% {
        opacity: 0;
        transform: translateX(100vw);
      }
      50.002% {
        opacity: 1;
        transform: translateX(100vw);
      }
      100% {
        transform: translateX(0);
      }
    }
    <button>Click me</button>
    <div>This is the div</div>