Categories
CSS Web development

CSS @keyframes Rule

CSS @keyframes Rule

The CSS @keyframes rule defines the animation code. The CSS animation is created step by step by changing from one set of CSS styles to another.

Define when the style change will happen in percent, or with the keywords “from”/ “to” (that is the same as 0% and 100%). 0% is the starting the animation, 100% is when the animation is ending.

Syntax:

@keyframes name {keyframes-selector {css-styles;}}

name – specifies the name of the animation.

keyframes-selector – percentage of the animation duration (0%-100%, or “form”/ “to”).

css-styles – one or more CSS style properties.

Example1:

<!DOCTYPE html>
<html>
<head>
<style> 
.square {
  width: 100px;
  height: 100px;
  background-color: #2a9d8f;
  position: relative;
  animation: move 5s infinite;
}

@keyframes move {
  0%   {left: 0px; background-color: #2a9d8f;}
  25%  {left: 100px; background-color: #264653;}
  50%  {left: 0px; background-color: #e76f51;}
  75%  {left: 100px; background-color: #f4a261;}
  100% {left: 0px; background-color: #e9c46a;}
}
</style>
</head>
<body>

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

</body>
</html>

Output:


Example2:

<!DOCTYPE html>
<html>
<head>
<style> 
.square {
  width: 100px;
  height: 100px;
  background: #2a9d8f;
  position: relative;
  animation: rotate 5s infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
</head>
<body>

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

</body>
</html>

Output:



Enjoy coding!

Read also:

Introduction to CSS Animation

CSS Transition VS. CSS Animation

CSS Reference