Search code examples
cssreactjscss-animations

How to make a smooth animation from the center of the screen to the top left corner of the screen?


I want to animate an image to move from the center of the screen to the top left corner smoothly

I tried with transitions but it's not working as intended.

const acoustic = document.querySelector('.acoustic');
document.body.addEventListener('click', () => acoustic.classList.toggle('selected'));
.acoustic {
  background-color: blue;
  height: 100px;
  width: 90vw;
}

.acoustic .guitar{
    display: flex;
    position: relative;
    top: 50%;
    right: -50%;
    transform: translate(-50%, -50%);
    animation: fadeIn 0.5s ease-in-out 0.5s forwards;
    height: 10vw;
    width: 10vw;
    transition: all 0.3s ease;
    background-color: red;
}

.acoustic.selected .guitar {
    display: flex;
    position: relative;
    top: 0;
    left: 0;
    height: 5vw;
}
<p>Click anywhere</p>
<div class="acoustic"><div class="guitar"></div></div>


Solution

  • The jank comes from the fact that you specify right in the first state, then left in the second state. Since you're not changing the same property you don't get a smooth transition.

    Change right: -50%; to left: 50%.

    const acoustic = document.querySelector('.acoustic');
    document.body.addEventListener('click', () => acoustic.classList.toggle('selected'));
    .acoustic {
      background-color: blue;
      height: 100px;
      width: 90vw;
    }
    
    .acoustic .guitar{
        display: flex;
        position: relative;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        animation: fadeIn 0.5s ease-in-out 0.5s forwards;
        height: 10vw;
        width: 10vw;
        transition: all 0.3s ease;
        background-color: red;
    }
    
    .acoustic.selected .guitar {
        display: flex;
        position: relative;
        top: 0;
        left: 0;
        height: 5vw;
    }
    <p>Click anywhere</p>
    <div class="acoustic"><div class="guitar"></div></div>