Sub topic 11
Animating a Dialog with CSS
This chapter assumes you can write basic CSS selectors and transitions, and that you know how to open a dialog with showModal() and close it with close(). It also assumes you have styled dialog and ::backdrop as covered in earlier chapters. Here you will make the dialog and its backdrop fade in and out.
Why dialogs are hard to animate
A closed dialog has display: none in the browser's default style sheet. An open one has display: block. A modal dialog also sits in the top layer, a browser-managed layer that draws above all other page content.
CSS transitions interpolate between two computed values on an element that is already rendered. Three things get in the way here:
displayis not animatable by default. It flips betweennoneandblockinstantly. Ifdisplaygoes tononeon close, the element vanishes in one frame and no fade-out can play.- The element has no "before" state on open. A transition needs a starting style. When the dialog goes from
display: noneto rendered, there is no earlier computed style to transition from, so it appears at its final style. - Top-layer membership ends immediately on close. Without extra work, the dialog leaves the top layer as soon as it closes. During a fade-out it would drop below other page content and the backdrop would vanish.
Recent CSS features solve each of these:
| Problem | CSS feature that solves it |
|---|---|
| `display` cannot be interpolated | `transition-behavior: allow-discrete`, or the `allow-discrete` keyword in the `transition` shorthand |
| No starting style on first render | `@starting-style` |
| Top layer is left immediately | The `overlay` property, transitioned with `allow-discrete` |
The state model
Think of the dialog as moving between two states. The [open] attribute is the switch. The browser sets it in show() and showModal() and removes it in close().
On open, the browser applies the @starting-style values for the first frame and then transitions to the [open] values. On close, the [open] rule no longer matches, so the base rule applies. Because display and overlay are transitioned discretely, the browser delays their change until the transition finishes.
The complete example
This is the stylesheet from the chapter plan. It fades in the dialog and its backdrop.
dialog {
opacity: 0;
transition:
opacity 200ms ease,
overlay 200ms allow-discrete,
display 200ms allow-discrete;
}
dialog[open] {
opacity: 1;
}
@starting-style {
dialog[open] {
opacity: 0;
}
}
dialog::backdrop {
background: rgb(0 0 0 / 0);
transition:
background 200ms ease,
overlay 200ms allow-discrete,
display 200ms allow-discrete;
}
dialog[open]::backdrop {
background: rgb(0 0 0 / 0.5);
}
@starting-style {
dialog[open]::backdrop {
background: rgb(0 0 0 / 0);
}
}Walk through it piece by piece.
The closed and open styles
The base rule dialog sets opacity: 0. This is the style the dialog has when it is closed, and the style it transitions to when it closes. The dialog[open] rule sets opacity: 1, which is the resting style while open.
The transition list
The transition property lists three entries:
opacity 200ms easefades the dialog.display 200ms allow-discretekeepsdisplay: blockin effect for the 200 ms of the exit transition before switching tonone. On entry, the switch toblockhappens at the start.overlay 200ms allow-discretekeeps the dialog in the top layer for the same period.overlayis a property that reflects top-layer status, with valuesnoneandauto. You cannot set it yourself. You can only transition it.
All three use the same duration. If the display and overlay durations are shorter than the opacity duration, the dialog disappears before the fade finishes.
The starting style
@starting-style supplies the "before" values for the first frame after the element starts rendering. Without it, the dialog would appear at opacity: 1 immediately and the fade-in would not run. The rule inside must match the same element and have a selector that applies on open. Here that is dialog[open].
The backdrop
::backdrop is a separate box with its own transitions. It needs its own base state, [open] state, @starting-style rule, and transition list. A common mistake is to animate only the dialog and leave the backdrop to snap in and out.
The backdrop selector dialog[open]::backdrop matches only while the dialog is open. The base rule dialog::backdrop supplies the transparent exit state.
A slide-and-fade variant
You can animate more than opacity. This variant also moves the dialog upward as it appears. It adds transform to the transition list and to the three states.
dialog {
opacity: 0;
transform: translateY(1rem);
transition:
opacity 250ms ease,
transform 250ms ease,
overlay 250ms allow-discrete,
display 250ms allow-discrete;
}
dialog[open] {
opacity: 1;
transform: translateY(0);
}
@starting-style {
dialog[open] {
opacity: 0;
transform: translateY(1rem);
}
}On close, the dialog fades out and slides back down, because the base rule sets the same values as the starting style. Keep the movement small. Large movements are distracting and are a problem for people who are sensitive to motion.
Respecting reduced motion
Some users set an operating-system preference to reduce motion. CSS exposes it through the prefers-reduced-motion media query. Cut the animation for those users and keep it as the default for everyone else, or the other way round. The safer pattern is to disable motion when the user asks for it:
@media (prefers-reduced-motion: reduce) {
dialog {
transform: none;
transition-duration: 1ms;
}
dialog[open] {
transform: none;
}
dialog::backdrop {
transition-duration: 1ms;
}
}This removes the slide and shortens the fades to a near-instant change. A small duration is used instead of removing the transition because the display and overlay entries should still complete normally. A fade is usually acceptable for reduced-motion users, but you can set transition-duration: 0s if you want no animation at all. In that case the dialog and backdrop change instantly, which is also valid.
Browser support and fallbacks
The features in this chapter are newer than the dialog element itself:
@starting-styleandtransition-behavior: allow-discreteare supported in current versions of Chrome, Edge, Safari, and Firefox. Check a compatibility table such as MDN's before relying on them for older browsers.- Transitioning
overlayis the most limited. Browsers that do not support it ignore that entry.
The animation is progressive enhancement. In a browser that lacks these features, the dialog still opens and closes correctly. It just appears and disappears instantly. You do not need JavaScript fallbacks. Do not make the layout or function of the dialog depend on the animation.
Common mistakes
- Missing
overlayon the dialog. The fade-in works, but on close the dialog drops out of the top layer at once. It may flash below other content or lose its backdrop mid-fade. - Missing
displayin the transition list. The dialog disappears instantly on close, with no fade-out. - Missing
@starting-style. The fade-out works, but the fade-in does not. - Animating only the dialog. The backdrop stays at its final color and pops in and out.
- Mismatched durations. If
displayoroverlayis shorter thanopacity, the element is removed mid-fade. - Putting the animation on
dialog:not([open])only. The base rule is the right place for the closed state. Keep the open-state values indialog[open]. - Animating
heightfrom or toauto. Plain CSS cannot interpolateautowithout extra features such asinterpolate-size. Prefer opacity and transform.
Testing the animation
You can check that the animation works without writing extra code.
- Open the page in a browser and trigger the dialog with
showModal(). The dialog and backdrop should fade in over the duration you set. - Press Escape. The dialog should fade out, not vanish.
- Open browser developer tools and slow animations down, for example with the Animations panel in Chrome or Edge. Watch whether the backdrop and the dialog fade together and whether the dialog stays above the page during the exit.
If the exit fade does not run, first check that display and overlay appear in the dialog's transition list, then check the durations.
Timing with the close event
The close event fires when the dialog closes. With an animated exit, the element is still visible for some time after close() is called, but the open attribute is already gone. The event does not wait for the fade. Do not use it as a signal that the animation has finished.
If you need to run code after the exit animation ends, listen for the transitionend event on the dialog. Filter by event.propertyName, because the event fires once per transitioned property:
const dlg = document.getElementById('dlg');
dlg.addEventListener('transitionend', (event) => {
if (event.target === dlg && event.propertyName === 'opacity' && !dlg.open) {
console.log('exit animation finished');
}
});The event.target === dlg check avoids reacting to transitions on child elements, which bubble up to the dialog. The !dlg.open check distinguishes the exit from the entry transition.
Also note that focus returns to the previously focused element when close() runs, not when the fade ends. This is usually fine for users, but you should not rely on it for timing.
Summary of the technique
- Put the closed look in the base
dialogrule and the open look indialog[open]. - Add
overlayanddisplayto thetransitionlist withallow-discrete, using the same duration as the visual properties. - Add an
@starting-stylerule that matchesdialog[open]and holds the entry values. - Repeat steps 1 to 3 for
::backdrop. - Reduce or remove motion under
prefers-reduced-motion: reduce.
Exercise
A developer adds opacity and @starting-style to a dialog. The fade-in works, but the dialog disappears instantly on close and the backdrop snaps off. Which two entries are missing from the transition list, and what does each do?
Show answer
display and overlay, each with allow-discrete. display ... allow-discrete holds display: block until the exit transition ends, so the fade-out can play. overlay ... allow-discrete keeps the dialog in the top layer for the same time, so it stays above the page and keeps its backdrop during the fade. The same entries are needed on ::backdrop.
Exercise
You set opacity 300ms and display 100ms allow-discrete on a dialog. What do you see when the dialog closes, and how do you fix it?
Show answer
The dialog is removed after 100 ms, when display switches to none, so the 300 ms fade is cut short. Set the display and overlay durations equal to the opacity duration, for example all 300 ms.
Exercise
Write the CSS rule that holds the entry values for a dialog that should start 1rem lower and fully transparent, then become visible when open.
Show answer
@starting-style {
dialog[open] {
opacity: 0;
transform: translateY(1rem);
}
}
The dialog[open] rule sets opacity: 1 and transform: translateY(0), and the base dialog rule sets the same values as the starting style so that the exit reverses the entry.