Animations make the website dynamic for users. Many believe that JavaScript is essential for this, but modern CSS allows for the creation of complex effects without a single line of JS code. Using CSS animations speeds up page loading and reduces the load on the browser, as they are hardware accelerated.
Basics of CSS Animations
To create an animation, you need to define keyframes using @keyframes. For example, let's create a smooth color change for a button:
@keyframes changeColor {
0% { background-color: #3498db; }
100% { background-color: #2ecc71; }
}
button {
animation: changeColor 2s infinite alternate;
}
This code makes the button change color every 2 seconds. The animation runs continuously due to infinite, and alternate makes it change direction on each repeat.
Animation of Object Movement
One of the most common effects is the smooth movement of an element. For example, let's create a block that moves left and right:
@keyframes move {
0% { transform: translateX(0); }
50% { transform: translateX(100px); }
100% { transform: translateX(0); }
}
.moving-block {
animation: move 3s infinite;
}
This effect can be applied to various elements to give the page dynamism.
CSS Transition: Smooth Style Changes
If you need to animate property changes without @keyframes, you can use transition. For example, let's create a hover effect on a button:
button {
background-color: #3498db;
transition: background-color 0.3s ease-in-out;
}
button:hover {
background-color: #2ecc71;
}
This approach makes the color change more pleasant without jarring.
Combining Effects
To achieve more complex effects, you can combine @keyframes and transition. For example, let's create a "pulsing" effect:
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
.pulsing-button {
animation: pulse 1.5s infinite;
}
Thus, CSS animations allow for the creation of dynamic and smooth effects without the need for JavaScript.