takeradi takeradi - 5 months ago 15
CSS Question

Multiple CSS Transforms on class change using the CSS animation property

How do I activate the CSS animation when the

.move
class is added to the
.box
using only CSS? The animation should translate first and when the translate has finished the rotate should begin where the translate ended. Also, how do I make the end state of the animation to be persistent at 100% and reset to 0% when the
.move
class is removed?



$(".test").click(function(){
$(".box").toggleClass("move")
});

body{
padding: 45px;
}

.test{
margin-top: 15px;
}

.box{
height: 45px;
width: 45px;
background: black;
}

.move{
background: blue;
}

.box{
animation: slide 0.5s, rotate 0.5s;
animation-delay: 0s, 0.5s;
}

@keyframes slide{
100%{
transform: translateX(450px);
}
}

@keyframes rotate{
100%{
transform: rotate(45deg);
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">

</div>
<button class="test">Toggle</button>




Answer

You can add multiple transforms by placing them together:

transform:translateX(450px) rotate(45deg);

To do this with a key-frame animation, you want to do all stages as a single animation. You will want to apply the animation to the .move class and set animation-fill-mode: forwards to persist the last frame until the class is removed.

$(".test").click(function(){
	$(".box").toggleClass("move")
});
body{
  padding: 45px;
}

.test{
  margin-top: 15px;
}

.box{
  height: 45px;
  width: 45px;
  background: black;
}

.move{
  background: blue;
  animation: slide 1s;
  animation-fill-mode: forwards;
}


@keyframes slide{
  50%{
    transform: translateX(450px);
    
  }
  100%{
    transform:translateX(450px) rotate(45deg);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  
</div>
<button class="test">Toggle</button>