CSS animation allows for the creation of animation without JS or Flash, with keyframes and every CSS property. It offers more advantages than a simple transition.
To create a CSS animation, you need to create a keyframe:
/* The animation code */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
from means at the start of the animation, while to means at the end of the animation.
You can also be more precise with the timeframe by setting the percentage:
/* The animation code */
@keyframes example {
0% {background-color: red;}
25% {background-color: yellow;}
50% {background-color: blue;}
100% {background-color: green;}
}
To trigger the animation, you need to call it in the specific div with the CSS properties:
animation-name: example;
animation-duration: 4s;
For our header navigation, the keyframe would be:
/* The animation code */
@keyframes sticky-animation {
from {transform: translateY(-90px);}
to {transform: translateY(0px);}
}
transform: is a new type of position in CSS that allows you to move an element in a 2D or 3D environment. With translateY, we're moving the element in the Y-axis. Also, we named the keyframes sticky-animation:
header.sticky {
position: fixed;
top: 0;
background-color: #212121;
background-image: none;
animation-name: sticky-animation;
animation-duration: 0.3s;
}
The last part will be to call the animation in the class .sticky, with a duration of 0.3s.
We now have a sticky navigation that works perfectly, with a cool animation!