Sub topic 4
Fading in elements added with JavaScript
This chapter assumes you know how CSS transitions work (transition-property, duration, timing function). It also assumes you can write basic JavaScript that creates elements and appends them to the page. Earlier chapters explained the before-change style and the @starting-style rule. Here you apply them to a common case: elements your script adds after the page has loaded.
Why inserted elements appear instantly
A transition needs two values for a property: one before the change and one after. The browser takes the before value from the element's previous style. A newly inserted element has no previous style, because it did not exist in the rendered page a moment ago.
So when script runs list.append(card), the browser computes the card's style for the first time. It finds opacity: 1, which is the only value it has, and draws the card at full opacity. Nothing changes, so no transition runs.
The @starting-style rule fixes this. It supplies a before-change style for the element's first style update. The browser then has two values to compare, and the transition runs.
A complete working example
This page combines the CSS and JavaScript from the topic. Save it as an HTML file and open it in a recent browser.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fade-in cards</title>
<style>
.card {
padding: 1rem;
margin-block: 0.5rem;
background: #eef3ff;
border-radius: 0.5rem;
opacity: 1;
transform: translateY(0);
transition: opacity 0.4s ease, transform 0.4s ease;
@starting-style {
opacity: 0;
transform: translateY(1rem);
}
}
</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>Each click adds a card that fades in while sliding up by 1rem. The script contains no animation code. It creates the element, sets a class, and inserts it.
Three details in the CSS matter:
- The main rule holds the final values (
opacity: 1,transform: translateY(0)). The nested@starting-styleblock holds only the values to start from. - The
transitiondeclaration is in the main rule. The browser reads transition settings from the after-change style, so they must apply to the element in its normal state. - Every property you want to animate must appear in both places. If you leave
transformout of the starting style, onlyopacityanimates.
What the browser does during insertion
The key idea is the first style update. It is the first time the browser resolves styles for an element. For an element created by script, it happens after insertion, when the browser next updates rendering.
Because the browser resolves both values in the same update, you do not need to wait a frame or force a layout. Your script only has to put the element in the document.
What people did before @starting-style
Before this rule, authors had to create the starting state by hand. The table compares the usual techniques.
| Technique | How it works | Drawback |
|---|---|---|
| Class added after insertion | Insert with a hidden class, then remove it | The class swap must happen in a later frame |
| Double `requestAnimationFrame` | Wait two frames, then change the class | Timing is fragile and the code is hard to read |
| Forced reflow | Read `el.offsetHeight` between insertion and the class change | Costs a layout and looks like a bug to later readers |
| `@starting-style` | Declare the start values in CSS | Needs a browser that supports it |
If you maintain older code that uses one of the first three, you can usually delete the JavaScript timing and keep only the CSS.
When starting styles apply
A starting style is used only for an element's first style update, or when it goes from display: none to a displayed state. It is not a general "from" value. These cases follow from that rule:
- Elements present at page load. They also get a first style update, so a
.cardin the initial HTML fades in on load. - Already rendered elements. Adding a class later does not use the starting style. An ordinary transition handles that change.
- Elements moved in the DOM. Calling
append()on an element that is already in the page removes it and inserts it again. Its style is discarded, so the starting style applies again and the element fades in at the new position. - Detached elements. An element you create but have not inserted has no style update yet. The starting style is used when you insert it.
- Elements inside a hidden ancestor. If you insert a card into a container that is
display: none, the card has no rendered style yet. Its entry transition runs when the container is shown. - Several elements in one task. If your script appends ten cards in a loop, all ten get their first style update together and fade in at the same time.
Staggering a batch of insertions
Ten cards fading in together can look flat. You can offset them with a custom property that the script sets on each element and the CSS uses to compute a delay.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Staggered cards</title>
<style>
.card {
padding: 0.75rem;
margin-block: 0.4rem;
background: #eef3ff;
border-radius: 0.5rem;
opacity: 1;
transform: translateY(0);
transition:
opacity 0.4s ease calc(var(--i, 0) * 60ms),
transform 0.4s ease calc(var(--i, 0) * 60ms);
@starting-style {
opacity: 0;
transform: translateY(1rem);
}
}
</style>
</head>
<body>
<button id="add-batch">Add 8 cards</button>
<div id="list"></div>
<script>
document.getElementById('add-batch').addEventListener('click', () => {
const list = document.getElementById('list');
for (let i = 0; i < 8; i++) {
const card = document.createElement('div');
card.className = 'card';
card.style.setProperty('--i', i);
card.textContent = 'Card ' + (i + 1);
list.append(card);
}
});
</script>
</body>
</html>The delay is part of the element's normal transition value, not the starting style. It therefore also applies to any later transition on opacity or transform, such as a hover effect. If that is a problem, keep the stagger on a property that nothing else changes, or add a second rule that overrides transition for the states where you do not want a delay.
Limits of this chapter's technique
Starting styles handle entry only. Removing an element with card.remove() still takes it out of the document immediately, and a transition cannot play on an element that no longer exists. Exit animations need a different approach, covered in the chapters on transition-behavior: allow-discrete and display.
You should also consider motion preferences. Users who set "reduce motion" in their operating system should not get sliding cards. A later chapter shows the prefers-reduced-motion media query for this.
Support and fallback
@starting-style works in current Chromium-based browsers, Safari and Firefox, but older versions ignore it. Browsers that do not understand the rule skip it, and the element simply appears at its final state with no animation. This makes the feature a progressive enhancement. The page works everywhere, and the animation is a bonus where it is supported.
Common mistakes
- Putting
transitiononly in the starting style. The browser reads transition settings from the normal rules. Put them in the main rule. - Forgetting a property. A property missing from
@starting-styledoes not animate, even if it changes in other states. - Expecting a second run. A card that is already visible does not replay its entry when a class changes. Remove it and insert it again if you want a replay.
- Using
height: autoas an end value. Animating toautois a separate topic. Keep your entry animations to properties such asopacityandtransform.
Exercise
A script builds a card with document.createElement, sets its class, and appends it to the list. The card's CSS has opacity: 1 and a transition on opacity, but no @starting-style rule. Why does the card appear instantly, and what is the smallest CSS change that makes it fade in over 0.5s?
Show answer
A new element has no before-change style, so on its first style update the browser sees only opacity: 1 and has nothing to transition from. Add a starting style with the start value inside the card rule, and make sure the transition duration is 0.5s: .card { opacity: 1; transition: opacity 0.5s; @starting-style { opacity: 0; } }. The transition declaration stays in the main rule, not in the starting style.
Exercise
You call list.append(existingCard) on a card that is already in the list, to move it to the end. Does it fade in again, and why?
Show answer
Yes. append() removes the element and inserts it again, which discards its computed style. The next style update counts as a first style update, so the starting style supplies the before-change values and the entry transition runs again.