Sub topic 1
Recap: how transitions use the before-change style
Prerequisites
Assume you know CSS selectors and the cascade, the transition property, display: none, and basic JavaScript for changing classes or inserting elements. Familiarity with dialog and popover is helpful later.
How a transition starts
A CSS transition interpolates between two computed styles. The browser compares the before-change style with the after-change style, then animates properties such as opacity or transform.
.card {
opacity: 1;
transform: translateY(0);
transition: opacity 0.4s ease, transform 0.4s ease;
}
.card.is-hidden {
opacity: 0;
transform: translateY(1rem);
}When JavaScript adds is-hidden, the browser already knows the card's old style. It can animate from the old values to the new values.
Why newly rendered elements do not animate
A newly rendered element usually has no before-change style in the document. The browser sees its first computed style as its current state, not as a change from another state. Therefore, this rule does not automatically animate a new card:
.card {
opacity: 1;
transition: opacity 0.4s ease;
}The element begins at opacity: 1. There is no earlier opacity: 0 value for the transition to use. The same problem occurs when an element changes from display: none to a rendered state.
Giving an element a starting point
The @starting-style at-rule supplies the missing before-change style. It applies only when an element begins a style update, such as its first render.
.card {
opacity: 1;
transform: translateY(0);
transition: opacity 0.4s ease, transform 0.4s ease;
@starting-style {
opacity: 0;
transform: translateY(1rem);
}
}The nested form keeps the starting values beside the final values. A top-level form is also valid:
@starting-style {
.card {
opacity: 0;
}
}The starting rule participates in the cascade. A later or more specific rule can override it, so source order and specificity matter.
Fading in elements added with JavaScript
The same rule works when JavaScript inserts an element. The browser applies the starting style, then updates the element to the normal style.
<button id="add">Add card</button>
<div id="list"></div>
<style>
.card {
opacity: 1;
transition: opacity 0.4s ease;
@starting-style {
opacity: 0;
}
}
</style>
<script>
document.querySelector("#add").addEventListener("click", () => {
const card = document.createElement("div");
card.className = "card";
card.textContent = "New card";
document.querySelector("#list").append(card);
});
</script>Exercise
Why does a newly inserted .card fade in in this example?
Show answer
@starting-style gives the first style update an initial opacity of 0, and the normal rule changes it to 1, allowing the transition to run.