模态框打开与关闭动画
结合 Tailwind 过渡实用程序与 JavaScript class 切换,为模态框的进入和退出添加动画,带来流畅的用户体验。
模态框打开与关闭动画 是 CoddyKit 上的免费 Tailwind CSS Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Tailwind CSS Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Tailwind CSS Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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>Scale and Fade Dialog Entrance
The most common modal entrance animation is a scale-up with fade: the dialog starts slightly smaller and transparent, then grows to full size while becoming opaque. This mimics how modals appear in iOS and Android.
Add transition-all duration-300 to the dialog panel. Toggle scale-95 opacity-0 (initial hidden state) to scale-100 opacity-100 (visible state). The short duration of 300ms keeps the animation snappy.
<!-- Dialog panel -->
<div
id="dialog"
class="bg-white rounded-2xl shadow-2xl w-full max-w-md
transition-all duration-300
scale-95 opacity-0 pointer-events-none">
<!-- content -->
</div>
<script>
function openModal() {
const d = document.getElementById('dialog');
d.classList.remove('scale-95', 'opacity-0', 'pointer-events-none');
d.classList.add('scale-100', 'opacity-100', 'pointer-events-auto');
}
function closeModal() {
const d = document.getElementById('dialog');
d.classList.remove('scale-100', 'opacity-100', 'pointer-events-auto');
d.classList.add('scale-95', 'opacity-0', 'pointer-events-none');
}
</script>Slide-Up Animation for Mobile Sheets
On mobile, a bottom sheet slides up from the bottom of the screen instead of appearing in the center. This is more ergonomic for thumb-based interaction. Use fixed bottom-0 inset-x-0 to anchor the panel at the bottom, and translate-y-full as the initial hidden state that you toggle to translate-y-0.
Add a drag handle (w-10 h-1 rounded-full bg-gray-300 mx-auto mt-3) at the top to signal swipeability.
<div
id="sheet"
class="fixed bottom-0 inset-x-0 z-50 bg-white rounded-t-2xl shadow-2xl
transition-transform duration-300 ease-out
translate-y-full">
<!-- Drag handle -->
<div class="w-10 h-1 rounded-full bg-gray-300 mx-auto mt-3"></div>
<div class="px-6 py-5">
<h2 class="text-lg font-semibold text-gray-900">Share</h2>
<p class="mt-2 text-sm text-gray-600">Choose how you want to share this item.</p>
</div>
<div class="flex justify-end gap-3 px-6 pb-6">
<button onclick="closeSheet()" class="px-4 py-2 text-sm font-semibold border border-gray-300 rounded-lg">Cancel</button>
<button class="px-4 py-2 text-sm font-semibold text-white bg-blue-600 rounded-lg">Share</button>
</div>
</div>Easing Functions for Smooth Animations
The timing function determines how an animation accelerates and decelerates. Tailwind provides four easing utilities: ease-linear, ease-in, ease-out, and ease-in-out.
For modal entrances, use ease-out — the element starts fast and decelerates as it reaches its final position, which feels natural and satisfying. For exits, use ease-in — the element accelerates as it leaves, which feels purposeful. ease-in-out works well for reversible transitions like toggle actions.
<!-- Entrance: fast start, slow end -->
<div class="transition-all duration-300 ease-out
scale-95 opacity-0">
Modal entering
</div>
<!-- Exit: slow start, fast end -->
<div class="transition-all duration-200 ease-in
scale-95 opacity-0">
Modal exiting
</div>Waiting for Exit Animation to Complete
A common mistake is removing the modal from the DOM (or hiding with hidden) immediately when close is triggered. This cuts off the exit animation. Instead, wait for the animation to complete using the transitionend event before hiding the element.
Listen for the event with { once: true } so the handler runs only once per transition and does not accumulate. After the transition, add hidden or pointer-events-none to prevent user interaction with the invisible element.
<script>
function closeModal() {
const dialog = document.getElementById('dialog');
const backdrop = document.getElementById('backdrop');
// Start exit animation
dialog.classList.remove('scale-100', 'opacity-100');
dialog.classList.add('scale-95', 'opacity-0');
backdrop.classList.remove('opacity-100');
backdrop.classList.add('opacity-0');
// Wait for animation to finish, then hide
dialog.addEventListener('transitionend', () => {
dialog.classList.add('pointer-events-none');
backdrop.classList.add('pointer-events-none');
document.body.classList.remove('overflow-hidden');
}, { once: true });
}
</script>Cascading Animation for Backdrop and Dialog
Opening both the backdrop and dialog at exactly the same time can feel abrupt. A cascading animation opens the backdrop first and then the dialog a fraction of a second later, creating a layered reveal effect.
Achieve this by adding a delay-100 class to the dialog element so its transition starts 100ms after the backdrop's. Remove the delay for the close sequence to keep the exit fast.
<!-- Backdrop: starts immediately -->
<div id="backdrop"
class="fixed inset-0 bg-black/50 z-40
transition-opacity duration-300
opacity-0 pointer-events-none">
</div>
<!-- Dialog: starts 100ms after backdrop -->
<div id="dialog"
class="bg-white rounded-2xl shadow-2xl w-full max-w-md
transition-all duration-300 delay-100
scale-90 opacity-0 pointer-events-none">
<!-- content -->
</div>
<!-- On open: add opacity-100 to backdrop, then scale-100/opacity-100 to dialog (delay-100 handles the stagger) -->
<!-- On close: remove delay-100 from dialog before starting the exit --></i>Zoom-In Alert Modal
For critical alerts (errors, destructive confirmations), a zoom-in effect is more attention-grabbing than a gentle scale. Start the dialog at scale-50 and animate to scale-100 with a fast duration-150 for a snappy pop-in that commands attention.
Use this sparingly — overdoing dramatic animations desensitizes users. Reserve zoom-in for genuinely important prompts where you need the user's undivided attention.
<!-- Zoom-in alert -->
<div
id="alert-dialog"
class="bg-white rounded-2xl shadow-2xl w-full max-w-sm
transition-all duration-150 ease-out
scale-50 opacity-0">
<div class="p-6 text-center">
<div class="mx-auto w-14 h-14 rounded-full bg-red-100 flex items-center justify-center">
<svg class="w-7 h-7 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
</svg>
</div>
<h2 class="mt-4 text-lg font-bold text-gray-900">Critical Error</h2>
<p class="mt-2 text-sm text-gray-500">Your session has expired. Please log in again.</p>
<button class="mt-5 w-full py-2.5 bg-blue-600 text-white font-semibold rounded-lg">Sign In Again</button>
</div>
</div>Animating With CSS Classes vs Inline Styles
There are two approaches to modal animation in Tailwind: class toggling (which we have been doing) and inline style manipulation via JavaScript. Class toggling is the Tailwind way — it keeps styling in HTML classes and behavior in JavaScript cleanly separated.
Inline style manipulation (element.style.opacity = '0') breaks the utility-first approach and makes styles harder to audit. Stick to class toggling unless you need dynamic values that cannot be predetermined, such as animated positions based on user interaction coordinates.
// Class toggling (Tailwind approach) — preferred
function openModal() {
dialog.classList.remove('scale-95', 'opacity-0');
dialog.classList.add('scale-100', 'opacity-100');
}
// Inline style approach — avoid unless necessary
function openModalInline() {
dialog.style.transform = 'scale(1)';
dialog.style.opacity = '1';
// Hard to maintain, not visible in HTML
}Respecting Reduced Motion Preferences
Some users experience motion sickness from UI animations. CSS and Tailwind both respect the prefers-reduced-motion media query. Use motion-reduce:transition-none and motion-reduce:transform-none on animated elements to disable transitions for users who have requested reduced motion in their OS settings.
This is an accessibility requirement that is often overlooked. Adding these utilities ensures your animated modals do not cause discomfort or trigger motion sensitivity issues.
<div
id="dialog"
class="bg-white rounded-2xl shadow-2xl w-full max-w-md
transition-all duration-300 ease-out
motion-reduce:transition-none
scale-95 opacity-0">
<!-- dialog content -->
</div>Toast Notification Animation
A toast notification is a temporary, non-blocking message that slides in from the top or bottom corner of the screen. Use fixed bottom-4 right-4 z-50 for positioning, and animate it with translate-y-2 opacity-0 initially, transitioning to translate-y-0 opacity-100.
Auto-dismiss the toast after a few seconds using setTimeout. Tailwind's transition-all duration-300 handles both the entrance and the auto-exit fade-out smoothly.
<!-- Toast element -->
<div
id="toast"
class="fixed bottom-4 right-4 z-50
flex items-center gap-3 px-4 py-3 bg-gray-900 text-white text-sm rounded-xl shadow-xl
transition-all duration-300
translate-y-2 opacity-0 pointer-events-none">
<svg class="w-4 h-4 text-green-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
</svg>
Changes saved successfully!
</div>
<script>
function showToast() {
const t = document.getElementById('toast');
t.classList.remove('translate-y-2', 'opacity-0', 'pointer-events-none');
t.classList.add('translate-y-0', 'opacity-100');
setTimeout(() => {
t.classList.remove('translate-y-0', 'opacity-100');
t.classList.add('translate-y-2', 'opacity-0', 'pointer-events-none');
}, 3000);
}
</script>Quick Check
Test your understanding of Tailwind CSS Mastery concepts from this lesson.
Lesson Recap
In this lesson you learned: modal animations work by toggling opacity and scale utility classes (scale-95 opacity-0 to scale-100 opacity-100) with transition-all duration-300; exit animations require waiting for transitionend before hiding the element; and motion accessibility is handled with motion-reduce:transition-none to respect the prefers-reduced-motion OS setting. Next up we build dropdown menus.
用 AI 导师学习 HTML — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 30
- 课程
- 120
常见问题解答
「模态框打开与关闭动画」课时是免费的吗?
是的 — 「模态框打开与关闭动画」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Tailwind CSS Academy 课程的其余内容,请升级到 CoddyKit PRO。 Tailwind CSS Academy 课程共包含 4 节课。
「模态框打开与关闭动画」这节课中我会学到什么?
结合 Tailwind 过渡实用程序与 JavaScript class 切换,为模态框的进入和退出添加动画,带来流畅的用户体验。 你通过在浏览器中直接运行的动手代码来练习 Tailwind CSS Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Tailwind CSS Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Tailwind CSS Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「模态框打开与关闭动画」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Tailwind CSS Academy 课中编写并运行代码吗?
能。每节 Tailwind CSS Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 模态对话框结构
- 模态框打开与关闭动画
- 下拉菜单组件
- 无障碍模态框与下拉菜单