Tailwind CSS Academy · Aula

Animação de abertura e fechamento do modal

Anime a entrada e a saída do modal usando utilitários de transição do Tailwind combinados com a alternância de classes em JavaScript para uma experiência suave.

Aula 2 de 413 etapas

Animação de abertura e fechamento do modal é uma aula grátis de Tailwind CSS Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Tailwind CSS Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Tailwind CSS Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Grátis para começar

Aprenda HTML com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
30
Aulas
120

Perguntas Frequentes

A aula “Animação de abertura e fechamento do modal” é grátis?

Sim — o texto completo de “Animação de abertura e fechamento do modal” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Tailwind CSS Academy, atualize para CoddyKit PRO. O curso de Tailwind CSS Academy inclui 4 aulas no total.

O que vou aprender em “Animação de abertura e fechamento do modal”?

Anime a entrada e a saída do modal usando utilitários de transição do Tailwind combinados com a alternância de classes em JavaScript para uma experiência suave. Você pratica Tailwind CSS Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Tailwind CSS Academy?

Nenhuma experiência prévia é necessária. Tailwind CSS Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Animação de abertura e fechamento do modal”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Tailwind CSS Academy?

Sim. Cada aula de Tailwind CSS Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Estrutura de diálogo modal
  2. Animação de abertura e fechamento do modal
  3. Componente de menu suspenso
  4. Modais e menus suspensos acessíveis
← Voltar para Tailwind CSS Academy