How to Transition Transform in CSS: Simple Guide with Examples
To smoothly animate changes to the
transform property in CSS, use the transition property with transform as the target. For example, transition: transform 0.5s ease; will animate any transform changes over half a second with easing.Syntax
The transition property lets you animate changes to CSS properties smoothly. To animate transform, specify it as the property to transition, followed by duration and timing function.
- transform: The CSS property to animate.
- duration: How long the animation lasts (e.g.,
0.5sfor half a second). - timing-function: How the animation speed changes over time (e.g.,
ease,linear).
css
selector {
transition: transform 0.5s ease;
}Example
This example shows a square that smoothly rotates 45 degrees when you hover over it. The transition property animates the transform change.
css
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background: #f0f0f0;
}
.box {
width: 100px;
height: 100px;
background-color: #4a90e2;
transition: transform 0.5s ease;
cursor: pointer;
}
.box:hover {
transform: rotate(45deg);
}Output
A blue square in the center of the page that smoothly rotates 45 degrees clockwise when hovered over.
Common Pitfalls
Common mistakes when transitioning transform include:
- Not specifying
transformin thetransitionproperty, so no animation happens. - Using
transition: allwhich can cause performance issues if many properties change. - Forgetting to set an initial
transformstate, which can cause jumpy animations.
Always specify transform explicitly and set a starting transform value if needed.
css
/* Wrong: no transition on transform */ .box { transition: background-color 0.5s ease; } .box:hover { transform: scale(1.2); } /* Right: transition on transform */ .box { transition: transform 0.5s ease; transform: scale(1); } .box:hover { transform: scale(1.2); }
Quick Reference
| Property | Description | Example |
|---|---|---|
| transform | The CSS property to animate | transform: rotate(30deg); |
| transition-property | Which property to animate | transition-property: transform; |
| transition-duration | How long the animation lasts | transition-duration: 0.5s; |
| transition-timing-function | Speed curve of animation | transition-timing-function: ease; |
| transition | Shorthand for all transition properties | transition: transform 0.5s ease; |
Key Takeaways
Use
transition: transform duration timing-function; to animate transform changes smoothly.Always specify
transform explicitly in the transition property for best performance.Set an initial
transform value to avoid jumpy animations.Avoid using
transition: all to prevent unnecessary animations and improve performance.Use easing functions like
ease for natural-looking animations.