0Pricing
Tailwind CSS Academy · Leçon

Animation d’ouverture et de fermeture d’une fenêtre modale

Animez l’entrée et la sortie de la fenêtre modale avec les utilitaires de transition de Tailwind, associés à l’activation et à la désactivation de classes JavaScript pour une expérience fluide.

Animation d’ouverture et de fermeture d’une fenêtre modale est une leçon Tailwind CSS Academy gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Tailwind CSS Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Tailwind CSS Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

Questions Fréquemment Posées

La leçon « Animation d’ouverture et de fermeture d’une fenêtre modale » est-elle gratuite ?

Oui — le texte complet de « Animation d’ouverture et de fermeture d’une fenêtre modale » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Tailwind CSS Academy, passe à CoddyKit PRO. Le cours Tailwind CSS Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Animation d’ouverture et de fermeture d’une fenêtre modale » ?

Animez l’entrée et la sortie de la fenêtre modale avec les utilitaires de transition de Tailwind, associés à l’activation et à la désactivation de classes JavaScript pour une expérience fluide. Tu pratiques Tailwind CSS Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Tailwind CSS Academy ?

Aucune expérience préalable n'est requise. Tailwind CSS Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.

Combien de temps prend la leçon « Animation d’ouverture et de fermeture d’une fenêtre modale » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Tailwind CSS Academy ?

Oui. Chaque leçon Tailwind CSS Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Structure d’une boîte de dialogue modale
  2. Animation d’ouverture et de fermeture d’une fenêtre modale
  3. Composant de menu déroulant
  4. Fenêtres modales et menus déroulants accessibles
← Retour à Tailwind CSS Academy