Sub topic 2
Why newly rendered elements do not animate
This chapter assumes you can write a basic CSS transition with transition-property, a duration and a timing function. It also assumes you know what display: none does, and that you can add a class or insert an element with JavaScript. You don't need @starting-style yet. This chapter explains the problem it solves.
The symptom
Here is a page that looks like it should fade in a card on every click. It doesn't.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Card without entry animation</title>
<style>
.card {
opacity: 1;
transform: translateY(0);
transition: opacity 0.4s ease, transform 0.4s ease;
padding: 1rem;
border: 1px solid #888;
margin-top: 0.5rem;
}
</style>
</head>
<body>
<button id="add">Add card</button>
<div id="list"></div>
<script>
document.getElementById('add').addEventListener('click', () => {
const card = document.createElement('div');
card.className = 'card';
card.textContent = 'New card';
document.getElementById('list').append(card);
});
</script>
</body>
</html>The .card rule declares a transition on opacity and transform, so you might expect something to animate. Nothing does. Each card appears at full opacity in its final position.
The same thing happens when you switch an element from display: none to display: block. The element shows up at once, even with a transition declared on it.
Transitions need two styles
A CSS transition runs when the computed value of a property changes between two points in time. The browser compares:
- The before-change style: the computed style the element had after the previous style update.
- The after-change style: the computed style the element has after the current style update.
If a transitioned property has different values in these two styles, the browser starts a transition from the first value to the second. If the values are equal, or if one of the styles doesn't exist, no transition starts.
A transition therefore needs a "from" value, and it needs a browser that has already seen that value. Setting a new value in your CSS isn't enough. The browser must have rendered the old value first.
The first style update
An element has no before-change style until the browser has computed its style at least once while the element was being rendered. The first time an element gets a computed style is called its first style update. At that moment there is no earlier style to compare against, so the browser has nothing to transition from.
This is by design. If every element animated from some default value on page load, the whole page would flicker as it loaded. Transitions are meant for changes to something already on screen.
So in the example above:
document.createElement('div')creates an element that isn't in the document. It has no computed style.className = 'card'andappend(...)put it in the document.- At the next style update, the browser computes
opacity: 1andtransform: translateY(0)for the first time. - There is no before-change style, so no transition starts.
Setting opacity: 0 in JavaScript right after append doesn't help either, if both changes happen before the browser runs a style update. The browser only sees the final values.
Which cases have no before-change style
Three situations produce the same result.
| Situation | Why there is no before-change style |
|---|---|
| First page render | The element has never had a computed style. |
| Element inserted into the DOM | It wasn't in the document at the previous style update. |
| Element changes from `display: none` to a visible value | Elements with `display: none` aren't rendered, so they don't have a style that transitions can start from. |
The third row surprises many developers. An element with display: none is in the DOM, and you can read its computed style with getComputedStyle. But for transitions, an element that wasn't rendered at the previous style update is treated as if it didn't exist. Leaving display: none counts as a first style update.
The reverse direction fails too. When you set display: none, the element stops being rendered immediately. It doesn't wait for a fade-out. Exit animations have the same problem as entry animations, and a later chapter covers them.
The timeline
The diagram shows what happens when you add a class and the element goes straight from not rendered to rendered.
Seeing it in action
You can confirm that the rule is about rendering and not about your transition declaration. The next page lets you toggle a class on an element that is already visible. This does transition.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Transition on a rendered element</title>
<style>
.box {
width: 6rem;
height: 6rem;
background: steelblue;
opacity: 1;
transition: opacity 0.4s ease;
}
.box.faded {
opacity: 0.2;
}
</style>
</head>
<body>
<button id="toggle">Toggle</button>
<div class="box" id="box"></div>
<script>
document.getElementById('toggle').addEventListener('click', () => {
document.getElementById('box').classList.toggle('faded');
});
</script>
</body>
</html>The box is rendered when the page loads, so it has a before-change style. Each toggle changes opacity between two known values, and the browser animates the change. The transition code is the same as in the failing card example. Only the element's rendering history differs.
The old workaround: force a style update
Before @starting-style, developers created the missing before-change style by hand. They rendered the element in its starting state, forced the browser to compute that style, and then changed to the end state.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Entry animation with a forced style update</title>
<style>
.card {
opacity: 0;
transform: translateY(1rem);
transition: opacity 0.4s ease, transform 0.4s ease;
padding: 1rem;
border: 1px solid #888;
margin-top: 0.5rem;
}
.card.is-visible {
opacity: 1;
transform: translateY(0);
}
</style>
</head>
<body>
<button id="add">Add card</button>
<div id="list"></div>
<script>
document.getElementById('add').addEventListener('click', () => {
const card = document.createElement('div');
card.className = 'card';
card.textContent = 'New card';
document.getElementById('list').append(card);
// Reading a computed value forces the browser to run a style update now.
getComputedStyle(card).opacity;
card.classList.add('is-visible');
});
</script>
</body>
</html>This works because reading getComputedStyle(card).opacity makes the browser compute the card's style right away, with opacity: 0. That computation becomes the before-change style. Adding is-visible then produces an after-change style with opacity: 1, and a transition starts.
Another common version of this trick waits two animation frames with requestAnimationFrame before adding the class.
These workarounds have costs:
- The JavaScript is easy to get wrong. A minifier or a linter may remove a line that "does nothing", such as a bare
getComputedStyle(card).opacity. - Forcing a style update can force layout work too, which is slower when you do it many times.
- The starting state lives in the base rule, not in a separate declaration. The base
.cardrule has to describe the hidden state, and a second class describes the visible state. This is the reverse of how most people write CSS. - It requires JavaScript, even when the element was created by a framework or by server-rendered HTML.
- It doesn't help with
display: nonetoggles that you do through a class alone.
What the fix looks like
CSS now lets you say, in the stylesheet, what the before-change style should be for an element's first style update. That is the job of the @starting-style at-rule. You write the real, final values in the main rule, and you write the values to animate from inside @starting-style:
.card {
opacity: 1;
transform: translateY(0);
transition: opacity 0.4s ease, transform 0.4s ease;
@starting-style {
opacity: 0;
transform: translateY(1rem);
}
}With this rule, the failing page from the start of the chapter works without changing its JavaScript. The next chapter covers the syntax and rules of @starting-style in detail. For now, remember what it replaces. It gives the browser a before-change style where none would otherwise exist.
Common mistakes at this stage
- Declaring the transition on the wrong state. If the hidden state is the only one that has
transition, the change back may not animate. Puttransitionon the base rule so it applies in both directions. - Expecting page load to animate. An element present in the initial HTML has no before-change style on first render. A fade-in on load needs the same fix as an inserted element.
- Changing a property before and after in one task. Setting
opacity: 0and thenopacity: 1in the same JavaScript task, with no style update between them, produces one style change. The browser only sees the final value. - Assuming
display: noneis just another value. It is a rendering switch. A transition can't start from an element that wasn't being rendered. - Testing only in a reused page. After you've toggled an element once, it has a before-change style. If you only test the second and later toggles, you can miss a failure that happens on the first one.
Summary
A transition needs a before-change style and an after-change style with different values. An element that is newly inserted, newly rendered, or newly switched from display: none has no before-change style at its first style update. The browser therefore skips the transition. The old workaround forced an early style update from JavaScript. The modern approach declares the starting values in CSS with @starting-style.
Exercise
A script creates a div with a rule transition: opacity 0.5s and opacity: 1, then appends it to the page. The div appears at once, without fading. Explain why, in terms of the before-change style.
Show answer
The div was not in the document at the previous style update, so it has no before-change style. Its first style update computes opacity: 1 with nothing to compare against, so the browser starts no transition. The transition declaration is correct, but a transition needs two styles, and only one exists.
Exercise
You change a hidden panel from display: none to display: block by toggling a class. The panel has opacity: 1 and transition: opacity 0.3s. Does it fade in? Why or why not?
Show answer
No. An element with display: none isn't rendered, so it has no before-change style at the previous style update. Switching to display: block counts as the first style update, and no transition starts. You need a starting style, such as one declared with @starting-style, to give the transition a "from" value.
Exercise
In the forced-style-update workaround, what does getComputedStyle(card).opacity; accomplish, and why is it placed between append and classList.add?
Show answer
Reading a computed value makes the browser run a style update immediately. That update computes the card with the hidden values (opacity: 0), which become its before-change style. Adding the is-visible class afterwards creates an after-change style with different values, so a transition starts. If the line were missing, both changes would be merged into one style update and no transition would run.