Sub topic 2
Writing a transition: property, duration, timing function and delay
This chapter assumes you know basic CSS selectors and the cascade, common properties such as color, opacity and background-color, and pseudo-classes such as :hover and :focus-visible. You should also be able to toggle a class with JavaScript.
A transition is a rule that tells the browser to change a property gradually when its computed value changes, instead of switching instantly. You do not describe the in-between frames. You describe which property, how long, how it speeds up and slows down, and whether to wait first. The browser fills in the rest.
The four parts of a transition
A transition has four settings. Each one has a longhand property.
| Longhand | What it controls | Initial value |
|---|---|---|
| `transition-property` | Which properties are transitioned | `all` |
| `transition-duration` | How long the change takes | `0s` |
| `transition-timing-function` | How progress is distributed over time | `ease` |
| `transition-delay` | How long to wait before starting | `0s` |
The initial duration is 0s. This is the most common reason a transition seems to do nothing: with a zero duration, the change is instant, so no transition ever runs. Any transition needs a duration greater than zero.
Here is the example from the plan, which uses the shorthand:
.button {
background-color: #2563eb;
transform: translateY(0);
transition: background-color 200ms ease-out, transform 200ms ease-out;
}
.button:hover,
.button:focus-visible {
background-color: #1d4ed8;
transform: translateY(-2px);
}The button changes its background color and vertical position over 200 milliseconds when hovered or focused. When the state ends, it transitions back.
Notice where the transition declaration lives. It sits on the base rule, .button, not on :hover. The transition that applies to a change is the one in effect on the element after the change. That detail matters in the next section.
Where to put the transition
Because the declaration in effect after the change is used, placement controls whether each direction animates.
.menu-item {
background-color: white;
}
.menu-item:hover {
background-color: #e0e7ff;
transition: background-color 300ms ease-out;
}Hovering fades the color in over 300 ms. Moving the pointer away changes the color back instantly, because the :hover rule no longer applies and the base rule has no transition. This asymmetry can be useful. A common pattern is a slow entry and a fast exit:
.menu-item {
background-color: white;
transition: background-color 100ms ease-in;
}
.menu-item:hover {
background-color: #e0e7ff;
transition-duration: 300ms;
}Here, going into the hover state takes 300 ms, and leaving it takes 100 ms. If you want the same behavior in both directions, put the transition on the base rule only.
The shorthand and how it is parsed
The transition shorthand takes one or more comma-separated transitions. Each one can contain up to four values:
transition: <property> <duration> <timing-function> <delay>;The values are mostly recognized by type, so order is flexible, with one rule: the first time value is the duration, and the second time value is the delay. So transition: opacity 1s 2s means a 1 second duration and a 2 second delay, never the reverse.
.panel {
transition: opacity 1s ease-in 2s;
}Leaving out values gives the initial values. transition: opacity 1s is the same as opacity 1s ease 0s.
A common mistake is writing transition: 0.3s and expecting it to be narrowly scoped. With no property named, the property defaults to all, so every animatable property that changes will transition.
Choosing the property
transition-property accepts these values:
all: every animatable property that changes. This is the default.none: no transition.- One or more property names, separated by commas.
all is convenient, but it has costs. It can animate properties you did not intend to animate, such as width changes triggered by a media query or a font change from a class swap. It can also start expensive layout-affecting transitions by accident. Listing properties explicitly is the safer habit:
.card {
transition-property: opacity, transform;
transition-duration: 250ms, 400ms;
transition-timing-function: ease-out, cubic-bezier(0.2, 0.8, 0.2, 1);
}When you use longhands with lists, the lists are matched by position. The first property gets the first duration and the first timing function, the second gets the second, and so on. If a list is shorter than the property list, it repeats. If it is longer, the extra values are ignored. So transition-duration: 250ms applies 250 ms to every listed property.
Duration
transition-duration takes a time in seconds (s) or milliseconds (ms). Negative values are invalid. For interface feedback, a rough range works well:
- Small state changes such as hover colors: 100 to 200 ms.
- Elements moving a short distance: 200 to 300 ms.
- Larger panels or overlays: 300 to 500 ms.
Anything much longer starts to feel like waiting. Exit motions are usually a little shorter than entry motions, since the user has already decided to dismiss the element.
Timing functions in brief
transition-timing-function describes how progress through the transition is spread over the duration. The keywords are ease (the default), linear, ease-in, ease-out and ease-in-out. You can also write your own curve with cubic-bezier() or jump in discrete steps with steps(). The next chapter covers these in detail. For now, remember that ease-out, which starts fast and ends slowly, suits elements that respond to user input, because the movement starts immediately.
Delay
transition-delay waits before the transition starts. A positive delay holds the old value until the delay passes. A negative delay starts the transition partway through, as if it had already been running for that amount of time.
.tooltip {
opacity: 0;
transition: opacity 150ms ease-out 400ms;
}
.trigger:hover + .tooltip {
opacity: 1;
}The tooltip waits 400 ms after the hover begins, so it does not flash up when the pointer only passes over the trigger. Be careful with delays on the base rule: a delay applies to the return trip as well, so the tooltip above also waits 400 ms before it begins to fade out. To avoid that, set the delay only on the rule for the active state, as in the earlier menu example.
Delays are also how you stagger a list of items:
.list li {
opacity: 0;
transition: opacity 300ms ease-out;
}
.list.is-open li {
opacity: 1;
}
.list.is-open li:nth-child(2) {
transition-delay: 100ms;
}
.list.is-open li:nth-child(3) {
transition-delay: 200ms;
}What happens when a transition is interrupted
Transitions can be interrupted. If the user hovers and then leaves before the 200 ms are up, the browser does not jump to the end value first. It starts a new transition from the current in-progress value back toward the original value. The result is smooth reversal.
The new transition uses a shortened duration so that the reversal takes about as long as the part of the movement already completed. This means a quick hover and un-hover does not produce a full-length slide back.
Things that prevent a transition from running
When a transition does not appear, check these causes in order:
- The duration is zero. The initial value is
0s, so you must set a duration. - The property cannot be interpolated. The browser needs two values it can blend. Changing
displayfromnonetoblockhas no in-between values in a normal transition. Chapter 14 covers the newer tools for that case. - The start value is
auto. Transitioningheightfrom0toautodoes not animate, becauseautois not a number the browser can blend. - The element has just been inserted. An element that did not exist before has no earlier style to transition from, so its first style is simply applied.
- The value does not change. Setting a property to the value it already has produces no transition.
- A more specific rule overrides the transition. Check the cascade for another
transitiondeclaration winning.
Reacting to the start and end
Transitions fire events you can listen for. The browser dispatches transitionend once for each property that finishes, so a rule that animates two properties triggers it twice. Filter on event.propertyName:
const button = document.querySelector('.button');
button.addEventListener('transitionend', (event) => {
if (event.propertyName === 'transform') {
console.log('Transform transition finished');
}
});If a transition is cancelled, for example because the property is changed to a different target mid-flight and the original never completes, transitionend does not fire for the abandoned one. Do not rely on it for critical logic. A later chapter covers events in full.
Triggering with a class
Hover is not the only trigger. Any change to a computed value starts a transition, including one caused by a class that JavaScript adds:
const panel = document.querySelector('.panel');
const toggle = document.querySelector('.panel-toggle');
toggle.addEventListener('click', () => {
panel.classList.toggle('is-open');
});.panel {
opacity: 0;
transform: translateY(8px);
transition: opacity 250ms ease-out, transform 250ms ease-out;
}
.panel.is-open {
opacity: 1;
transform: none;
}Each click toggles the class, and the panel fades and slides in either direction. Because the transition sits on .panel, it applies both ways.
Summary of decisions
- Name the properties you want to animate instead of using
all. - Put a transition on the base rule for symmetric motion, or on the state rule for asymmetric motion.
- Keep interface durations between 100 and 500 ms.
- Use delays sparingly, and remember that they apply to the return trip when set on the base rule.
- Always confirm the duration is above zero when debugging.
Exercise
A link has a { color: black; transition: color 200ms; } and a:hover { color: red; transition-delay: 1s; }. Describe what happens when the pointer enters the link, and what happens when it leaves.
Show answer
When the pointer enters, the :hover rule applies, so its delay of 1s is used. The color stays black for 1 second, then fades to red over 200 ms. When the pointer leaves, the :hover rule no longer applies, so the base rule's transition is used, with a delay of 0s. The color fades back to black over 200 ms right away.
Exercise
Write a transition shorthand that animates opacity over 300 ms with ease-in, and transform over 500 ms with ease-out after a 100 ms delay.
Show answer
transition: opacity 300ms ease-in, transform 500ms ease-out 100ms; The first time value in each item is the duration. The second, if present, is the delay, so the 100ms applies only to transform.