Animate elements on insertion with @starting-style
Give a newly rendered element a starting opacity with @starting-style so the browser can run an entry transition without a JavaScript timing workaround.
A notice starts at display: none and snaps into view when you show it. Use @starting-style to give its opacity transition a starting value.
Supply the first rendered opacity
Save this as notice.html. The checkbox provides a way to reveal the notice with CSS and repeat the test.
<!doctype html>
<title>Notice entry</title>
<style>
.notice {
display: none;
opacity: 1;
transition: opacity 250ms ease;
}
#show:checked ~ .notice {
display: block;
}
@starting-style {
.notice {
opacity: 0;
}
}
@media (prefers-reduced-motion: reduce) {
.notice {
transition: none;
}
}
</style>
<input id="show" type="checkbox">
<label for="show">Show preview</label>
<p class="notice">Your draft is ready to preview.</p>Open the file in a browser with @starting-style support. Check the box to see the notice fade in. Uncheck it to hide the notice and repeat the test.
When the notice has no rendered style from the previous update, @starting-style gives the browser an opacity to compare with the rendered value. The same rule can supply the starting value when you insert a new matching element into the document. A notice that is already visible uses its previous rendered style for an ordinary transition.
Put the starting rule where it can win
The rule still participates in the cascade. The example places it after the ordinary .notice rule, so its zero wins when the browser computes the starting style. If a selector with higher specificity sets the final opacity, use matching specificity inside the starting rule. Otherwise both values may resolve to one and you will see the snap again.
Browsers that skip the rule still show the notice. The reduced-motion query also lets readers see the notice without a fade. Keep the revealed state usable on its own so the transition can be dropped without losing information.
For a fade on the way out, you need the notice to remain rendered until opacity reaches zero. That is a separate display transition.