CSS Transitions
Transitions
CSS transitions animate changes from one property value to another over time. They are commonly used for hover effects, focus states, menus, and UI feedback.
A transition needs two things:
- a property value that can change (for example on
:hover) - a
transitionrule that defines duration and behavior
Basic example:
.btn {
background: #2563eb;
color: #fff;
padding: 10px 16px;
border-radius: 10px;
transition: background-color .2s ease;
}
.btn:hover {
background: #1d4ed8;
}
The shorthand transition typically includes:
transition-propertytransition-durationtransition-timing-functiontransition-delay(optional)
Example with separate properties:
.box {
transition-property: background-color;
transition-duration: 300ms;
transition-timing-function: ease;
transition-delay: 0ms;
}
Tip: Avoid transition: all in real projects. It can animate unexpected properties and hurt performance. Prefer targeting specific properties.
Transition Timing
The timing function controls the speed curve of the transition.
Common values:
linear– constant speedease– slow start, fast middle, slow end (default)ease-in– slow startease-out– slow endease-in-out– slow start and endcubic-bezier()– custom curve
.link {
transition: color .2s ease-in-out;
}
.panel {
transition: transform .35s cubic-bezier(.2, .9, .2, 1);
}
Tip: For UI hover/press effects, durations between 150ms and 350ms usually feel natural.
Transition + Transform
Transforms are ideal for transitions because they animate smoothly and usually do not cause layout reflow.
Scale on hover:
.card {
transition: transform .2s ease, box-shadow .2s ease;
}
.card:hover {
transform: translateY(-2px) scale(1.02);
box-shadow: 0 12px 30px rgba(0,0,0,.12);
}
Button press effect:
.button {
transition: transform .08s ease;
}
.button:active {
transform: scale(0.98);
}
Common mistake: Don’t try to transition properties that are not animatable (for example display). For showing/hiding elements, animate opacity and transform instead.
.dropdown {
opacity: 0;
transform: translateY(6px);
transition: opacity .15s ease, transform .15s ease;
pointer-events: none;
}
.dropdown.is-open {
opacity: 1;
transform: translateY(0);
pointer-events: auto;
}
Summary
- Transitions animate changes between property values.
- Use timing functions to control the speed curve.
- For smooth UI, transitions + transforms (translate/scale) are a best practice.