모달 열기 및 닫기 애니메이션
Tailwind 전환 유틸리티와 JavaScript 클래스 토글을 결합해 모달이 부드럽게 나타나고 사라지도록 애니메이션을 적용합니다.
모달 열기 및 닫기 애니메이션은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 30
- 레슨
- 120
자주 묻는 질문
“모달 열기 및 닫기 애니메이션” 강의는 무료인가요?
네 — “모달 열기 및 닫기 애니메이션” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“모달 열기 및 닫기 애니메이션”에서 뭘 배우나요?
Tailwind 전환 유틸리티와 JavaScript 클래스 토글을 결합해 모달이 부드럽게 나타나고 사라지도록 애니메이션을 적용합니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“모달 열기 및 닫기 애니메이션” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 모달 대화상자 구조
- 모달 열기 및 닫기 애니메이션
- 드롭다운 메뉴 컴포넌트
- 접근성을 고려한 모달과 드롭다운