Transitions that skip the start

You will see why a class added right after an insert never animates, and which fix to use instead.

ArticleMotion
01

The class that does nothing

A CSS transition does not run when you add a class in the same task that inserted the element, unhid it or set its start style. The browser batches style changes and works them out once, so it only ever sees the final state and has nothing to animate from. To fix it, make the browser compute the start state first. You can force a style read, wait a frame, declare the start with @starting-style, or give both ends to the Web Animations API.

Below are the bug and the most common fix, driven by the same button. Both lanes show the same card and add the same in class. The only difference is one line on the right.

Same card, same class, one extra line Interactive
class added in the same task
forced read, then class
Unhide from display: none
transition on .in only
Insert mode. Press Show both cards.

Press Show both cards. The left card appears at full opacity, already in place. The right card fades in and rises. The readout listens for transitionrun, the event the browser fires when it creates a transition. That proves the left card is not just too fast to see. On the left, no transition is ever created.

Now turn on Unhide from display: none. The cards are no longer inserted. They already exist and start hidden, like a menu, a dialog or a toast waiting for its moment. This is the version of the bug most people actually hit. Before each run the script hides both cards and lets the browser style them hidden, as if they had been hidden since an earlier frame. Then it removes display: none and adds the class. The verdict is the same: no transition on the left, a transition on the right.

</> The bug and the one-line fix, for inserts and unhides.Show code
// Broken: the start state is never computed
list.append(card);
card.classList.add('in');

// Fixed: the read forces style and layout first
list.append(card);
card.getBoundingClientRect();
card.classList.add('in');

// Unhiding has the same bug and the same fix
menu.hidden = false;
menu.getBoundingClientRect();
menu.classList.add('open');

A different bug with the same symptom. Turn on the second switch. It moves the transition declaration off the base rule and onto .in only. Press Show both cards, then Remove .in. The right card still fades in, because the browser takes the transition settings from the after-change style, and that style now matches .in. The removal snaps in both lanes. Once .in is gone, nothing declares a transition any more. If your entry works and your exit snaps, check where transition lives before you hunt for a timing problem.

</> Declare the transition where both directions can see it.Show code
/* Entry animates, exit snaps */
.card.in { opacity: 1; transition: opacity .3s; }

/* Both directions animate */
.card { opacity: 0; transition: opacity .3s; }
.card.in { opacity: 1; }

The rest of this article explains why the read works, what it costs, and the three cleaner alternatives.

02

The browser only looks once

Setting a class or a style property does not restyle anything right away. It marks the element as dirty, meaning its styles need to be worked out again. The browser does that work later, when it prepares the next frame. It does it sooner only if your script asks for a value that depends on it.

A transition needs two computed values: the one before the change and the one after. If you set the start style and the end style in the same task, the start style is never computed. The demo below tries to snap the card to the left with transition: none, then slide it back.

Snap left, then slide back Interactive
Read getBoundingClientRect() between
Switch off. Press Slide in.

With the switch off, clicking does nothing at all. In one task, the browser sees no transition, a left offset, the original transition and no offset. It resolves all of that into no change. Turn the switch on and the read forces the browser to compute the start state on the spot. The card jumps left, and the second set of changes now has a start to animate from. The readout shows how long that forced read took in your browser.

One level deeper. The CSS Transitions spec describes transitions in terms of style change events. These are the moments when the browser brings computed styles up to date. A transition starts only when a property's computed value differs between one style change event and the next. The spec has a second rule that explains the first demo: an element that was not rendered at the previous style change event gets no transitions. A freshly inserted element has no before-change style, and neither does one coming out of display: none. That is why the Unhide switch in the first demo fails on the left even though the hidden card had been styled before: hidden was its last state, and a hidden element has nothing to transition from.

03

What a forced read costs

A forced read is often called a forced reflow or forced synchronous layout. It makes the browser do the style and layout work right now instead of at the next frame. For one card that work is tiny. The cost appears when reads and writes alternate. Every write dirties the page again, and every read has to clean it up. This pattern is called layout thrashing.

240 dots, any list size Interactive
0 items already in the list. Read after each: not run. Read once: not run.

Your browser measures both times with performance.now(), and they include the inserts themselves. Some browsers round timers, so very small values can look coarse.

Both buttons insert 240 dots that fade in. The first one reads layout after each insert, so the browser recomputes style and layout 240 times. The second inserts every dot, reads once, then adds every class. The dots look exactly the same.

Now drag the range to put up to 2,000 items in the list before the dots arrive. When you release it, both strategies run again and the readout prints both times and the ratio between them. Watch which number moves. The read-once version still does a single layout, with a little more to place. The interleaved version does 240 forced layouts, and each one can have to revisit the items that share the container with the new dot. The readout shows whether that happens in your browser: if the interleaved time grows with the list size while the read-once time barely moves, each of those layouts is paying for the whole list. On a real page, everything that shares a layout with your list plays the role of those extra items.

</> Write everything, read once, then add the classes.Show code
const cards = items.map(makeCard);
list.append(...cards);         // all the writes
list.getBoundingClientRect();  // one forced read
cards.forEach(card => card.classList.add('in'));

Reads do not all cost the same. getBoundingClientRect(), offsetWidth and scrollTop force both style and layout. Reading a value like getComputedStyle(card).opacity needs style only, and for a transition that is enough. Calling getComputedStyle(card) without reading a property does nothing. The object it returns is live, and the work happens only when you read from it.

04

Wait for a frame, or two

Instead of forcing the work early, you can let the browser render the start state normally and add the class afterwards. requestAnimationFrame (rAF) runs a callback just before the next frame. It sounds like the right tool, but one call is not enough. Each button below runs its strategy 20 times in a row on the same card and counts the runs where the browser fired transitionrun.

One entry, six strategies, 20 runs each Interactive
Another rAF reads layout first
Pick a strategy. Each one runs 20 times.

Press One rAF, then Double rAF, and read the counts. Where the browser follows the frame order described below, one rAF scores 0/20 and a double rAF scores 20/20. The readout also shows the median time until the browser reported the transition. Double rAF reports later than the forced reflow, because it waits at least one extra frame.

Now turn on Another rAF reads layout first. It registers a second rAF callback before yours, the way a scroll tracker or a layout library might, and that callback calls getBoundingClientRect(). Run One rAF again and watch the count jump, though your code did not change. The other script computed the start state for you. Remove that script, or let its callback run after yours, and your entry breaks again. That is what flaky means here: one rAF works only when something else happens to read style first.

One level deeper. After your click handler finishes, the event loop reaches a rendering step. The HTML spec fixes the order inside it: run rAF callbacks, then update style and layout, then paint. A class added in the first rAF callback is applied before that frame's style update. That puts it in the same batch as the insertion. The second callback runs one frame later, after the start state has been computed and painted.

</> The second frame is the one that counts.Show code
list.append(card);
requestAnimationFrame(() => {
  // this frame's style update has not run yet
  requestAnimationFrame(() => card.classList.add('in'));
});

A trap when you test this yourself. If the insert itself runs inside a rAF callback, for example in an animation loop, one rAF passes every time. The card is inserted during a frame, so that frame's style update computes its start state before your next rAF adds the class. That is why each run in this demo starts in a fresh task with setTimeout. A test that inserts from a loop can tell you one rAF is fine when your click handler will still fail.

The cost of a double rAF is one frame of delay, about 17 ms on a 60 Hz display. There is also a catch: browsers pause rAF in background tabs, so an entry queued in a hidden tab waits until the tab is visible again. In exchange, you never force layout. That makes double rAF a fair choice on heavy pages where a forced layout would be expensive.

05

Declare the start in CSS

@starting-style fixes the problem at its source. It gives the browser the before values to use when an element has no previous style. That happens on its first style update after insertion, and when it leaves display: none. You write no script at all.

Cards added with append() only Interactive
@starting-style rule
Press Add a card. The readout will report what your browser did with the rule.

The script adds each card with a single append() and nothing else. With the rule on, the readout reports what your browser did: either it supports @starting-style and the card transitioned, or it ignored the block and the card appeared without motion. Turn the rule off and the same cards appear instantly, because the base rule is all the browser has.

</> The start state lives next to the end state.Show code
.card {
  opacity: 1;
  transform: none;
  transition: opacity .4s, transform .4s;
}
@starting-style {
  .card { opacity: 0; transform: translateY(16px); }
}
@media (prefers-reduced-motion: reduce) {
  .card { transition: opacity .4s; }
}

Starting values go through the cascade like any other declaration. If your base rule has higher specificity, it wins and the entry never animates. Give the @starting-style rule the same specificity and put it after the base rule. Inside a nested rule you can write @starting-style { opacity: 0; } directly.

If your readout says the rule was ignored, your browser predates it. Chrome and Edge shipped it in version 117 in 2023, Safari in 17.5 and Firefox in 129, both in 2024. Ignoring the block is a safe way to fail, because the element just appears. The rule covers entry only. An exit that ends in display: none also needs transition-behavior: allow-discrete. If your element also changes size as it appears, accordions without the jump covers that part of the problem.

06

Replays and the Web Animations API

The same batching also breaks replaying a CSS animation. If a ring class is already on the element, adding it again changes nothing. Removing it and adding it back in one task changes nothing either. The browser only sees the end result, and the class is still there.

Ring the bell again Interactive
Reflow between remove and add
Class clicks: 0, CSS animation started: 0. animate() runs: 0.

With the switch off, the first click rings the bell and later clicks do nothing. The animationstart counter stops moving. Turn the switch on and every click replays. The read makes the browser compute the bell without the animation, which cancels it, before the class comes back. Any feedback that has to replay on every action depends on this. The confirmation in a save you can see land is one example.

</> Remove, reflow, add.Show code
bell.classList.remove('ring');
void bell.offsetWidth; // computes the bell with no animation
bell.classList.add('ring');

The Web Animations API (WAAPI) avoids the problem completely. element.animate() takes the start and end keyframes as arguments, so the browser never has to work out a before state. Each call creates a new animation. That is why the second button replays every time without a read.

</> An entry where script owns both ends.Show code
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const frames = reduce
  ? [{ opacity: 0 }, { opacity: 1 }]
  : [{ opacity: 0, transform: 'translateY(16px)' },
     { opacity: 1, transform: 'none' }];

list.append(card); // its CSS already shows the end state
card.animate(frames, { duration: 400, easing: 'ease-out' });

One level deeper. CSS transitions, CSS animations and WAAPI animations share one model underneath. The browser represents all three as Animation objects, and document.getAnimations() returns them together. Animating transform and opacity through WAAPI is no slower than doing it in CSS. WAAPI costs something else: the motion lives in script. The element's resting style must already be the end state, or it snaps back when the animation finishes. fill: 'forwards' hides that by keeping the animation alive and overriding your styles. Reduced motion is also your job, as the code above shows.

07

Pick the cheapest fix

All four fixes make the same entry work. They differ in what they cost and where the motion lives.

Reach for @starting-style first for elements that are inserted or unhidden. It needs no script, forces no work and fails safely in old browsers.

Use animate() when script decides the motion. For example, the start might depend on where the user clicked, or you might need the finished promise to run the next step.

Use one forced read when you are keeping class-based transitions for a single element, or replaying a CSS animation. If many elements enter together, write them all, read once, and never read inside the loop.

Use a double rAF when a forced layout would be expensive and a one-frame delay is acceptable. Avoid it in code that may run in a background tab.

Tune your own entry below. Set the duration and the distance, pick a strategy, and press Preview to feel it. The code block rewrites itself with your values, including the reduced-motion fallback, so you can copy exactly what you previewed.

Tune it, then copy it Interactive
Strategy: @starting-style. Press Preview.
</> Your entry, with your values.Show code
.card { transition: opacity 300ms ease-out, transform 300ms ease-out; }
/* same specificity as .card, placed after it */
@starting-style {
  .card { opacity: 0; transform: translateY(16px); }
}
@media (prefers-reduced-motion: reduce) {
  .card { transition: opacity 300ms ease-out; }
}

// JS: list.append(card); and nothing else

If the bug is already spread across a codebase, hand the search to your coding agent. This prompt describes the patterns this article measured.

</> A ready prompt for auditing same-task class adds.Show code
Audit this codebase for CSS entry transitions that cannot run.
Find every place where an element is appended, inserted or unhidden
(display: none removed, the hidden attribute removed) and a class or
style that should transition is set in the same task, including inside
a single requestAnimationFrame or a setTimeout(fn, 0).
For each one:
- If the start state can live in CSS, add an @starting-style rule with
  the same specificity as the base rule, placed after it.
- If script decides the motion, use element.animate() with both keyframes.
- Otherwise add one forced read before the class, and move reads out of loops.
Also flag transitions declared only on a state class, not the base rule.
Keep or add a prefers-reduced-motion fallback that drops movement.
List each change with its file and line.

Quick answers. The short versions, for when you come back to this page.

Why does my transition not run when I add a class? The browser computes style once for the whole task, so it never sees the start state. Compute the start first with one forced read, or declare it with @starting-style.

Why does one requestAnimationFrame not fix it? rAF callbacks run before that frame's style update, so the class lands in the same batch as the insert. A second, nested rAF runs after the start state has been computed.

Which browsers support @starting-style? Chrome and Edge since version 117 (2023), Safari since 17.5 and Firefox since 129 (both 2024). Older browsers ignore the block, and the element simply appears.

Can I animate an element into display: none? Yes, but only with transition-behavior: allow-discrete and display in the transition list. Without them the element disappears at the start of the exit.

Avoid setTimeout(fn, 0). The timer is just another task, and it can run before or after the next frame. The entry works on one machine and fails on another. When an animation works only sometimes, the start state is usually being computed by accident, as the switch in section 4 showed, and one of the four fixes makes it reliable.

Every fix also needs the accessibility basics. Keep entry motion short, and under prefers-reduced-motion: reduce drop the movement and keep at most a fade, as every demo here does. An entering element should never take keyboard focus unless the user asked for it. If the new content matters, announce it through an aria-live region rather than relying on motion. The same restraint applies to small controls like elastic toggles: the motion confirms a change, but it is never the only signal.

Do not animate what nobody caused. Entry motion helps when it answers an action, like a card someone just added or a message that just arrived. Skip it for content present on page load and for long lists. Twenty staggered fades make the page feel slower without explaining anything.

Keep reading: fading out to display: none · how easing curves change the feel of the motion

08

Quick answers

Why doesn't my CSS transition run when I add a class?
The browser batches style changes and computes them once, when it prepares the next frame. If you insert an element, or set its start style, and add the class in the same task, the browser only sees the final state. It has no before value to animate from, so it never creates a transition. A newly inserted element, or one leaving display: none, has no previous style at all.

How do I make a transition run after appending an element?
Make the browser compute the start state before you add the class. The most common fix is a forced read, such as calling getBoundingClientRect() between append() and classList.add(). Cleaner options are @starting-style in CSS, a double requestAnimationFrame, or element.animate() with explicit start and end keyframes. For many elements, insert them all, read once, then add every class.

Why doesn't a single requestAnimationFrame fix the transition?
rAF callbacks run before the browser updates style in the same rendering step. A class added in the first callback lands in the same style batch as the insertion, so there is still no start state. A nested second rAF runs one frame later, after the start state has been computed and painted. The cost is about one frame of delay, roughly 17 ms on a 60 Hz display.

What is @starting-style and which browsers support it?
@starting-style is a CSS at-rule that gives the browser before values for an element that has no previous style. That covers its first style update after insertion and the moment it leaves display: none. Current Chrome, Edge, Firefox and Safari have supported it since 2024. Older browsers ignore the block, so the element simply appears without motion, which is a safe way to fail.

How do I replay a CSS animation by re-adding the same class?
If you remove and re-add a class in one task, nothing changes, because the browser sees only the end result. Remove the class, force a read such as void el.offsetWidth, then add the class again. Or call element.animate() with keyframes instead. Each call creates a new animation, so it replays every time without a forced read.

New deep dives, in your inbox.