Thomas Kim
Creating Smooth CSS Animations
CSS animations can transform static designs into engaging, interactive experiences. Let’s explore how to create smooth, performant animations.
CSS Transitions vs Animations
Transitions are best for simple state changes, while Animations offer more control with keyframes.
Transition Example
Here’s a simple hover effect using transitions:
.box {
width: 100px;
height: 100px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
transform: scale(1) rotate(0deg);
transition: all 0.5s ease-in-out;
cursor: pointer;
}
.box:hover {
transform: scale(1.5) rotate(45deg);
}Basic Transition Syntax
.button {
background-color: #3b82f6;
transition: background-color 0.3s ease-in-out;
}
.button:hover {
background-color: #1d4ed8;
}Keyframe Animations
For more complex animations, use @keyframes:
@keyframes bounce {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-20px);
}
}
.bouncing-ball {
animation: bounce 1s infinite;
}More Keyframe Examples
Spin Animation:
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.spinner {
animation: spin 2s linear infinite;
}Pulse Animation:
@keyframes pulse {
0%, 100% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.2);
opacity: 0.7;
}
}
.pulsing {
animation: pulse 1.5s ease-in-out infinite;
}Performance Tips
For smooth 60fps animations, only animate these properties:
transform(translate, rotate, scale)opacity
Avoid animating:
width,height(causes layout reflow)top,left(usetransform: translate()instead)background-color(can be expensive, but usually okay)
/* Bad - causes reflow */
.box {
transition: width 0.3s;
}
/* Good - uses transform */
.box {
transition: transform 0.3s;
}Conclusion
Master transitions for simple state changes and keyframes for complex animations. Always prioritize performance by animating transform and opacity properties!
Related
Jan 28, 2025