Search code examples
htmlcsstransformtransition

CSS transition Property not working with Transform


I have been trying to get some transition effect on my div boxes. But it doesent Work

.box{
            height: 200px;
            width: 400px;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: blueviolet;
            margin: 20px;
            border-radius: 20px;
            transform: translateX(200%);
             transition: transform 1s ease-in-out;
        }



.box.show{
    transform: translateX(0);
}

I am Aware that i am not using a button to add a class. i am just adding it manually and saving. But it dosent seem to work. here's the full code link


Solution

  • Including the show class on the box right off the bat will not show any animation. If you use setInterval (For demonstration purposes), you will see that the animation works.

    //Toggle the class every second
    setInterval(function(){ 
        document.getElementById('box').classList.toggle('show');
    }, 1000);
    .box{
      padding: 15px;
      height: 60px;
      width: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: blueviolet;
      margin: 20px;
      border-radius: 20px;
      transform: translateX(10%);
      transition: transform 1s ease-in-out;
      font-family: sans-serif;
    }
    
    .box.show{
        transform: translateX(0);
    }
    <!-- will animate since the show class is added after the initial render -->
    <div id="box" class="box">I'm a box with show class added after initial render 😃</div>
    
    <!-- Will not animate, the show class will determine it's initial transform -->
    <div class="box show">I'm a box with show already added 😞</div>