How to animate elements with CSS transitions and transforms
· Category: HTML & CSS
Short answer
CSS transitions animate property changes between states over time. CSS transforms move, rotate, scale, or skew elements without affecting layout, making them highly performant.
Steps
- Define the initial state of the element.
- Add
transition: property duration easing. - Change the property on hover, focus, or via a class toggle.
- Use
transforminstead oftop/leftfor movement to avoid layout thrashing.
Example
.box {
width: 100px;
height: 100px;
background: coral;
transition: transform 0.3s ease, background 0.3s ease;
}
.box:hover {
transform: scale(1.1) rotate(3deg);
background: darkorange;
}
Tips
- Animate only
transformandopacityfor the smoothest 60fps animations. - Use
will-change: transformsparingly to hint the browser for complex animations. - Avoid animating
width,height,margin, ortop/lefton many elements simultaneously.