How to Create Spin Animation in CSS: Simple Guide
To create a spin animation in CSS, use the
@keyframes rule to define the rotation and apply it with the animation property on an element. This makes the element rotate continuously or for a set time.Syntax
The spin animation uses the @keyframes rule to define the rotation from 0 to 360 degrees. Then, the animation property applies this rotation to an element with settings like duration and iteration count.
@keyframes spin: Defines the animation named 'spin'.from { transform: rotate(0deg); }: Start rotation at 0 degrees.to { transform: rotate(360deg); }: End rotation at 360 degrees.animation: spin 2s linear infinite;: Runs the spin animation for 2 seconds, smoothly, repeating forever.
css
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.element {
animation: spin 2s linear infinite;
}Example
This example shows a blue square that spins continuously using the CSS spin animation.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Spin Animation Example</title> <style> @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .spinner { width: 100px; height: 100px; background-color: #007bff; animation: spin 2s linear infinite; margin: 50px auto; border-radius: 10px; } </style> </head> <body> <div class="spinner" aria-label="Spinning blue square"></div> </body> </html>
Output
A blue square in the center of the page that spins smoothly and continuously.
Common Pitfalls
Some common mistakes when creating spin animations include:
- Forgetting to define
@keyframesbefore using the animation. - Not setting the
animation-iteration-countor using a finite number, so the spin stops unexpectedly. - Using
transform: rotate()incorrectly or with invalid units. - Missing vendor prefixes in older browsers (mostly legacy).
- Not setting the
animation-timing-functiontolinear, causing uneven speed.
Example of a wrong and right way:
css
.wrong-spin {
animation: spin 2s ease infinite; /* ease causes uneven speed */
}
.right-spin {
animation: spin 2s linear infinite; /* linear keeps speed steady */
}Quick Reference
Remember these key points for spin animations:
- Use
@keyframesto define rotation from 0 to 360 degrees. - Apply animation with
animation: spin 2s linear infinite;for smooth, continuous spin. - Use
lineartiming for steady speed. - Set
infiniteto keep spinning forever. - Use semantic HTML and ARIA labels for accessibility.
Key Takeaways
Define spin animation using @keyframes with rotate from 0deg to 360deg.
Apply the animation with linear timing and infinite iteration for smooth continuous spin.
Always include the animation property on the element you want to spin.
Avoid easing functions like ease for spin to keep rotation speed steady.
Use semantic HTML and ARIA labels to keep animations accessible.