Keyframe animations let you create smooth changes in how things look on a webpage over time. They help make websites feel alive and interesting.
Keyframe animations in CSS
@keyframes animation-name { 0% { /* styles at start */ } 50% { /* styles halfway */ } 100% { /* styles at end */ } } selector { animation-name: animation-name; animation-duration: time; animation-iteration-count: number | infinite; animation-timing-function: easing; }
The @keyframes rule defines the animation steps.
Use percentages (0% to 100%) to set styles at different times.
@keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } .box { animation-name: fadeIn; animation-duration: 2s; animation-fill-mode: forwards; }
@keyframes slideRight { 0% { transform: translateX(0); } 100% { transform: translateX(100px); } } .button { animation-name: slideRight; animation-duration: 1s; animation-iteration-count: infinite; animation-direction: alternate; }
This webpage shows a square box that smoothly changes its background color from light blue to light green and back continuously. The animation uses keyframes to define the color steps and CSS properties to control timing and repetition.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Keyframe Animation Example</title> <style> @keyframes colorChange { 0% { background-color: lightblue; } 50% { background-color: lightgreen; } 100% { background-color: lightblue; } } .animated-box { width: 150px; height: 150px; background-color: lightblue; animation-name: colorChange; animation-duration: 4s; animation-iteration-count: infinite; animation-timing-function: ease-in-out; border-radius: 1rem; margin: 2rem auto; display: flex; align-items: center; justify-content: center; font-family: sans-serif; color: #333; font-weight: bold; user-select: none; } </style> </head> <body> <main> <section> <div class="animated-box" aria-label="Box that changes color smoothly"> Watch me change! </div> </section> </main> </body> </html>
Always use animation-fill-mode: forwards; if you want the animation to keep the last style after finishing.
Use animation-iteration-count: infinite; to repeat animations endlessly.
Test animations in your browser's developer tools to adjust timing and effects easily.
Keyframe animations let you change styles smoothly over time.
Define steps with @keyframes and apply with CSS animation properties.
Use animations to make websites more engaging and interactive.