Offscreen Content - Animate Open/Close
Use CSS to create a native visual open and/or close animation for your modal/popover/dialog element, no JS required.
Demo
HTML
<!-- `popovertarget="pop-animation"` on the `button` connects to `id="pop-animation"` on the `dialog` -->
<button popovertarget="pop-animation">
Related Content with animation
</button>
<dialog popover id="pop-animation">
<h2>I'm Related Content with animation!</h2>
<p>Animation can be added to any popover type, and its <code>::backdrop</code>, via CSS.</p>
<p>Opening this popover fades-in the <code>::backdrop</code>, and slides the popover down as it fades in.</p>
<p>Closing the popover just closes both.</p>
</dialog>CSS
/* Animation for popover fade-in, and slide-down */
@keyframes dialogFadeIn {
from {
opacity: 0;
translate: 0 -1em;
}
to {
opacity: 1;
translate: 0 0;
}
}
/* Animation for backdrop fade-in */
@keyframes backdropFadeIn {
from {
background-color: rgb(0 0 0 / 0);
}
to {
background-color: rgb(0 0 0 / .5);
}
}
/* Add backdrop in case reduced-motion is requested */
dialog::backdrop {
background-color: rgb(0 0 0 / .5);
}
/* Apply both animations */
@media (prefers-reduced-motion: no-preference) { /* Be nice to others */
dialog {
animation: dialogFadeIn 250ms ease-in forwards;
&::backdrop {
animation: backdropFadeIn 250ms ease-in forwards;
}
}
}JS
No JS required.Baseline
CodePen
See the Pen on CodePen.