CSS - keyframes animations
In this article, we would like to show you how to use @keyframes
to create animations in CSS.
The @keyframes
rule controls the subsequent stages of CSS animation, defining the styles of keyframes (or subsequent points) during the duration of the animation.
To create keyframes animation with given animation-name
, we use the following syntax:
xxxxxxxxxx
@keyframes animation-name {
from {
/* styles at the beginning of the animation */
}
to {
/* styles at the end of the animation */
}
}
or we can use it with any percentage values from 0%
to 100%
:
xxxxxxxxxx
@keyframes animation-name {
0% {
/* styles at the beginning of the animation */
}
50% {
/* styles at the 50% of the animation */
}
100% {
/* styles at the end of the animation */
}
}
To assign the animation to the element, we need to specify the CSS selector (e.g .element
class) and add animation
property to it with specified animation-name
and animation-duration
time.
xxxxxxxxxx
.element {
animation: animation-name animation-duration;
animation: animation-name animation-duration; /* Safari, Chrome and Opera after 2012 (v.12.1) */
animation: animation-name animation-duration; /* Firefox before 2012 (v.16) */
animation: animation-name animation-duration; /* Internet Explorer */
animation: animation-name animation-duration; /* Opera before 2012 (v.12.1) */
}
Where:
animation-name
is - the name of our animation (e..gfadein
),-
animation-duration
is the time during which our animation will be performed (e.g.2s
).
Note:
There are more animation configuration options to specify, but in order for animation to work, these two needs to be specified.
In this example, we create fadein animation that goes from opacity: 0
to opacity: 1
making the element visible over specified time (2s
).
xxxxxxxxxx
<html>
<head>
<style>
.element {
animation: fadein 2s;
animation: fadein 2s; /* Safari, Chrome and Opera after 2012 (v.12.1) */
animation: fadein 2s; /* Firefox before 2012 (v.16) */
animation: fadein 2s; /* Internet Explorer */
animation: fadein 2s; /* Opera before 2012 (v.12.1) */
}
@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Legacy keyframes */
@-moz-keyframes fadein { /* Firefox before 2012 */
from { opacity: 0; }
to { opacity: 1; }
}
@-webkit-keyframes fadein { /* Safari, Chrome and Opera after 2012 (v.12.1) */
from { opacity: 0; }
to { opacity: 1; }
}
@-ms-keyframes fadein { /* Internet Explorer */
from { opacity: 0; }
to { opacity: 1; }
}
@-o-keyframes fadein { /* Opera before 2012 (v.12.1) */
from { opacity: 0; }
to { opacity: 1; }
}
</style>
</head>
<body>
<div class="element">
<div>some text...</div>
<div>some text...</div>
<div>some text...</div>
</div>
</body>
</html>