Categories
CSS Web development

CSS Transition VS. CSS Animation

You might think transitions and animations refer to the same thing, but they don’t. The CSS Transition can not change CSS properties which CSS Animation can do.

CSS transiton vs CS animation

CSS Transitions allow changing property values very smoothly, over a given duration. To create a transition effect, you must specify two things:

  1. The CSS property you want to add an effect to
  2. The duration of the effect

Note: If the duration is not specified, the transition will have no occur (default 0).

Example:

Hover over the div element (square) below, to see the transition effect (<div> element is changing the width from 100px to 200px). 

<!DOCTYPE html>
<html>
<head>
<style>
.square {
  width: 100px;
  height: 100px;
  background: #2a9d8f;
  transition: width 1s;
}

.square:hover {
  width: 200px;
}
</style>
</head>
<body>

<p>Hover over the square:</p>
<div class="square"></div>

</body>
</html>

Output:

Hover over the square:

Most often you can see transitions used on hover states, or when information on a page is added or removed. The hover states may be a subtle change in font color and information on the page may fade from invisible to visible. 

CSS Animations are a more powerful alternative to transitions. Rather than rely on a change from one beginning state to an end state. 

Where a transition goes only from A to B, the animation can go from A, B, C to D. Or any number of stages as needed. (To see the basics of CSS Animations click here.)

Example:

<!DOCTYPE html>
<html>
<head>
<style>
.square {
  width: 100px;
  height: 100px;
  background-color: #2a9d8f;
  position: relative;
  animation-name: example-2;
  animation-duration: 3s;
}

@keyframes example-2 {
  0%   {left:0px; top:0px;}
  25%  {left:100px; top:0px;}
  50%  {left:100px; top:100px;}
  75%  {left:0px; top:100px;}
  100% {left:0px; top:0px;}
}
</style>
</head>
<body>

<div class="square"></div>

</body>
</html>   

Output:

Click on the square to repeat the animation.




The CSS Transition is for creating a smooth transition from one state to another, and the CSS Animation for a more complex series of movements. 

Enjoy coding!