Sub topic 5
Triggering transitions with :hover, :focus-visible and class changes
This chapter assumes you can write a basic transition declaration, and that you know selectors, pseudo-classes and classList in JavaScript. Here the question is what starts a transition and what controls its direction.
What actually starts a transition
A transition does not start because you wrote a transition property. It starts when the computed value of a transitioning property changes on an element that is already rendered. The browser compares the old computed value with the new one, then interpolates between them for the duration you set.
Many things can change a computed value:
- A user-state pseudo-class starts or stops matching (
:hover,:focus-visible,:active,:focus-within). - JavaScript adds or removes a class, or changes an attribute such as
aria-expandedordata-state. - JavaScript sets an inline style.
- A media query starts or stops matching, for example when the viewport is resized.
If no computed value changes, nothing happens. If the element has no previous style, for example because it was just inserted, there is nothing to transition from. The last section of this chapter covers that case.
Pseudo-class triggers
The usual pattern puts the transition declaration and the resting values on the base rule. The triggered rule changes only the values.
.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);
}When the pointer enters, the computed values change and the button animates to the hover values. When the pointer leaves, the computed values change back, and the same transition on the base rule animates the return.
Why :focus-visible and not :focus
:focus matches whenever an element has focus, including after a mouse click. A button that lifts and changes color after every click looks odd. :focus-visible matches only when the browser decides the focus indicator should be shown. That is usually keyboard navigation. Pairing it with :hover gives keyboard users the same feedback that pointer users get.
:focus-within matches a container when any descendant has focus. It suits a form field wrapper that highlights while its input is focused.
.field {
border: 2px solid #94a3b8;
transition: border-color 150ms ease-out, box-shadow 150ms ease-out;
}
.field:focus-within {
border-color: #2563eb;
box-shadow: 0 0 0 3px rgb(37 99 235 / 0.25);
}Hover on touch devices
On touch screens, a tap often leaves :hover stuck on the last tapped element. Wrap hover-only effects in a media query so they apply only where hovering is possible:
@media (hover: hover) {
.card:hover {
transform: translateY(-4px);
}
}Keep the :focus-visible rule outside this query so keyboard users still get feedback.
Asymmetric transitions: which rule owns the timing
The transition that runs is the one declared on the element in its destination state. When the button goes from resting to hovered, the browser reads the transition value from the hovered rule, which is usually inherited from the base rule. When it goes back, the browser reads it from the resting state.
You can use this to make the two directions behave differently:
.menu-item {
background-color: transparent;
/* Used when leaving hover: a slow fade out */
transition: background-color 400ms ease-in;
}
.menu-item:hover {
background-color: #e2e8f0;
/* Used when entering hover: a fast response */
transition: background-color 100ms ease-out;
}Entering is quick, so the interface feels responsive. Leaving is slower, so the highlight fades gently. Delays work the same way. A transition-delay placed only on the hover rule delays the start of the hover effect but not the return.
Triggering with class changes
Pseudo-classes depend on the user's pointer and keyboard. Class changes let your code decide when a transition runs. This is the usual way to build menus, accordions and toasts.
.panel {
opacity: 0;
transform: translateX(16px);
transition: opacity 250ms ease-out, transform 250ms ease-out;
}
.panel.is-open {
opacity: 1;
transform: none;
}const toggle = document.querySelector('#panel-toggle');
const panel = document.querySelector('.panel');
toggle.addEventListener('click', () => {
const open = panel.classList.toggle('is-open');
toggle.setAttribute('aria-expanded', String(open));
});The same effect works with attribute selectors, which keeps the visual state and the accessibility state in sync:
.panel {
opacity: 0;
transition: opacity 250ms ease-out;
}
[aria-expanded="true"] + .panel {
opacity: 1;
}With this version the CSS reads aria-expanded directly. There is no separate class to keep consistent with it.
Interrupted transitions
Users move the pointer in and out quickly. If the trigger reverses while a transition is running, the browser does not jump to the end. It starts a new transition from the current interpolated value back toward the original. The browser also shortens the duration of the reversal, so a half-finished transition takes about half the time to return. You get smooth reversals without extra code.
Common problems
| Symptom | Cause | Fix |
|---|---|---|
| Nothing animates | The property is not animatable, or the value does not change | Check the computed value in dev tools; see the chapter on animatable properties |
| `display: none` to `block` jumps | `display` has no in-between values | Animate `opacity` and `visibility`, or use `@starting-style` and discrete transitions |
| Height does not animate to `auto` | `auto` cannot be interpolated | Animate `max-height`, use `grid-template-rows`, or use `interpolate-size` where supported |
| Hover flickers at the edge | The transform moves the element out from under the pointer | Put the hover rule on a stationary wrapper |
| Everything animates, including unwanted properties | `transition: all` | List the properties explicitly |
| Newly inserted element appears with no transition | No earlier style to transition from | Use `@starting-style` or add the class one frame later |
The flicker problem in detail
Suppose a card moves up 4px on hover. If the pointer is at the card's bottom edge, the card moves away and the pointer is no longer over it. :hover stops matching, the card moves back, :hover matches again, and the card jitters. Fix this by putting :hover on a wrapper that does not move, and transforming the child:
.card-wrap:hover .card,
.card-wrap:focus-within .card {
transform: translateY(-4px);
}
.card {
transition: transform 200ms ease-out;
}Avoid transition: all
transition: all 300ms is convenient, but it animates every property that changes, including ones you added later or did not intend. It can cause layout shifts when a rule adds width or margin. It also makes dev tools output harder to read. Name the properties instead.
Newly inserted elements
If JavaScript inserts an element and adds its "open" class in the same frame, the browser never computes a "closed" style first, so no transition runs. The modern fix is @starting-style, which a later chapter covers. Until then, remember that a transition needs a before state that was actually rendered.
Summary of the model
- Declare the transition on the element, with explicit property names.
- Change a computed value through a pseudo-class, class, attribute, inline style or media query.
- The browser reads the transition settings from the destination state and interpolates.
- If the trigger reverses mid-flight, the browser transitions back from the current value.
Exercise
A menu item has transition: background-color 400ms on .menu-item and transition: background-color 100ms on .menu-item:hover. How long does the highlight take to appear when the pointer enters, and how long to fade when the pointer leaves? Why?
Show answer
It appears in 100ms and fades out over 400ms. The browser uses the transition settings of the destination state. Entering hover, the destination is the :hover rule, which says 100ms. Leaving hover, the destination is the base rule, which says 400ms.
Exercise
A card translates up 6px on :hover. Users report that it jitters when the pointer is near its bottom edge. What causes this, and how do you fix it without removing the effect?
Show answer
The card moves out from under the pointer, so :hover stops matching and the card moves back, which makes :hover match again. Move the :hover selector to a stationary wrapper element (for example .card-wrap:hover .card) and apply the transform to the inner card.