Modal Open and Close Animation
Animate the modal entrance and exit using Tailwind transition utilities combined with JavaScript class toggling for a smooth user experience.
Why Animate Modals
Animating a modal's entrance and exit serves a functional purpose beyond aesthetics. A sudden appearance can startle users; a smooth fade-in contextualizes the modal's arrival and helps users understand where it came from. An exit animation signals that the interaction is completed and the user is returning to the page.
Tailwind's transition utilities make it straightforward to animate opacity and scale together, creating a polished fade-and-scale effect that matches the quality of native mobile UI patterns.
Fade-In Backdrop Animation
The backdrop should fade in when the modal opens and fade out when it closes. Add transition-opacity duration-300 to the backdrop element. Toggle opacity-0 (hidden) and opacity-100 (visible) via JavaScript.
The backdrop must remain in the DOM (not use hidden) for the fade to work — instead, start it as opacity-0 pointer-events-none and toggle to opacity-100 pointer-events-auto.
<!-- Backdrop with fade -->
<div
id="backdrop"
onclick="closeModal()"
class="fixed inset-0 bg-black/50 z-40
transition-opacity duration-300
opacity-0 pointer-events-none">
</div>
<script>
function openModal() {
document.getElementById('backdrop').classList.remove('opacity-0', 'pointer-events-none');
document.getElementById('backdrop').classList.add('opacity-100', 'pointer-events-auto');
}
function closeModal() {
document.getElementById('backdrop').classList.remove('opacity-100', 'pointer-events-auto');
document.getElementById('backdrop').classList.add('opacity-0', 'pointer-events-none');
}
</script>All lessons in this course
- Modal Dialog Structure
- Modal Open and Close Animation
- Dropdown Menu Component
- Accessible Modals and Dropdowns