0Pricing
Tailwind CSS Academy · 강의

모달 대화상자 구조

고정 위치 지정과 z-index 유틸리티를 사용해 배경 오버레이, 스크롤 가능한 콘텐츠 영역, 닫기 버튼이 있는 중앙 정렬 모달을 만듭니다.

모달 대화상자 구조은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Tailwind CSS Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is a Modal Dialog

A modal dialog is an overlay panel that appears on top of the page to capture the user's attention for a specific task — confirmation, a form, or detailed information — before returning them to the underlying page.

A modal consists of three parts: a backdrop overlay that dims the background, the dialog panel centered on screen, and a close mechanism (a button, Escape key, or backdrop click). All three must work together for a polished, accessible component.

Full-Screen Backdrop Overlay

The backdrop dims the page content behind the modal, focusing the user's attention on the dialog. Use fixed inset-0 bg-black/50 z-40 to cover the entire viewport with a 50% opaque black layer.

The backdrop should be a separate element from the dialog panel so you can independently animate them. Clicking the backdrop should close the modal — this is achieved with a JavaScript click handler on the backdrop element.

<div
  id="modal-backdrop"
  class="fixed inset-0 bg-black/50 z-40"
  onclick="closeModal()">
</div>

Centering the Dialog Panel

The dialog panel sits inside a centering container that uses fixed inset-0 flex items-center justify-center z-50 p-4. This container covers the full viewport as a flex container that centers its single child — the dialog box — both horizontally and vertically.

The p-4 ensures the dialog has breathing room from the screen edges on small screens, preventing it from touching the sides on mobile devices.

<!-- Centering container -->
<div class="fixed inset-0 flex items-center justify-center z-50 p-4">
  <!-- Dialog panel -->
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
    <!-- Modal content -->
  </div>
</div>

Dialog Header With Close Button

The modal header contains the dialog title and a close button. Use flex items-center justify-between px-6 py-4 border-b border-gray-100 to space the title and close button on opposite ends of the header row.

The title uses text-lg font-semibold text-gray-900 and the close button is a small icon button at the far right. The button must have an aria-label='Close modal' for screen reader users who cannot see the × icon.

<div class="flex items-center justify-between px-6 py-4 border-b border-gray-100">
  <h2 class="text-lg font-semibold text-gray-900" id="modal-title">
    Confirm Action
  </h2>
  <button
    onclick="closeModal()"
    aria-label="Close modal"
    class="p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100
           rounded-lg transition-colors">
    <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
    </svg>
  </button>
</div>

Dialog Body Content

The modal body holds the main content of the dialog. Use px-6 py-5 for comfortable padding. For long content, constrain the height with max-h-96 overflow-y-auto so the modal does not grow taller than the viewport.

Body text uses text-sm text-gray-600 leading-relaxed for readable paragraph spacing. Add icons or illustrations for visual clarity in confirmation and alert dialogs.

<div class="px-6 py-5">
  <div class="flex items-start gap-4">
    <!-- Warning icon -->
    <div class="flex-shrink-0 w-12 h-12 rounded-full bg-red-100 flex items-center justify-center">
      <svg class="w-6 h-6 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>
    <div>
      <p class="text-base font-semibold text-gray-900">Delete this record?</p>
      <p class="mt-1 text-sm text-gray-600 leading-relaxed">
        This action cannot be undone. All data associated with this record will be permanently removed from our servers.
      </p>
    </div>
  </div>
</div>

Dialog Footer With Action Buttons

The modal footer holds the action buttons. Use flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-100 to right-align the buttons and visually separate them from the body content.

Place the secondary action (Cancel) to the left of the primary action (Confirm/Delete) to match the spatial convention of safe action on the left and destructive action on the right.

<div class="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-100">
  <button
    onclick="closeModal()"
    class="px-4 py-2 text-sm font-semibold text-gray-700 border border-gray-300
           rounded-lg hover:bg-gray-50 transition-colors">
    Cancel
  </button>
  <button
    class="px-4 py-2 text-sm font-semibold text-white bg-red-600
           rounded-lg hover:bg-red-700 transition-colors">
    Delete Record
  </button>
</div>

Showing and Hiding the Modal

The modal starts hidden with hidden on both the backdrop and the centering container. When triggered, JavaScript removes hidden from both elements and adds overflow-hidden to the body to prevent background scrolling while the modal is open.

The close function reverses all three operations. Connect the trigger to any button with an onclick handler.

<script>
  const modal = document.getElementById('modal');
  const backdrop = document.getElementById('modal-backdrop');

  function openModal() {
    modal.classList.remove('hidden');
    backdrop.classList.remove('hidden');
    document.body.classList.add('overflow-hidden');
  }

  function closeModal() {
    modal.classList.add('hidden');
    backdrop.classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
  }

  // Escape key closes the modal
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') closeModal();
  });
</script>

Scrollable Modal for Long Content

When modal content is longer than the available viewport height, make only the body scrollable while the header and footer remain fixed. Apply max-h-screen overflow-hidden flex flex-col to the dialog panel, and flex-1 overflow-y-auto to the body section.

This prevents the modal from growing off-screen and keeps the action buttons always visible without the user needing to scroll past the content.

<div class="fixed inset-0 flex items-center justify-center z-50 p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg
              max-h-[90vh] flex flex-col">
    <!-- Fixed header -->
    <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100 flex-shrink-0">
      <h2 class="text-lg font-semibold">Terms of Service</h2>
      <button onclick="closeModal()" aria-label="Close">&times;</button>
    </div>
    <!-- Scrollable body -->
    <div class="flex-1 overflow-y-auto px-6 py-5">
      <p class="text-sm text-gray-600 leading-relaxed">
        Very long terms of service content that may exceed the viewport height...
        <!-- many paragraphs -->
      </p>
    </div>
    <!-- Fixed footer -->
    <div class="flex justify-end gap-3 px-6 py-4 border-t border-gray-100 flex-shrink-0">
      <button onclick="closeModal()" class="px-4 py-2 text-sm font-semibold text-gray-700 border border-gray-300 rounded-lg">Decline</button>
      <button class="px-4 py-2 text-sm font-semibold text-white bg-blue-600 rounded-lg">Accept</button>
    </div>
  </div>
</div>

Modal Size Variants

Modals come in different sizes depending on their content. Control the size with max-w-* on the dialog panel:

  • Small: max-w-sm — for simple confirmation dialogs
  • Medium: max-w-lg — for forms and moderate content
  • Large: max-w-2xl — for detailed views or complex forms
  • Full: max-w-5xl — for image viewers or rich content

Always include a minimum w-full so the modal shrinks appropriately on small screens even when the max-width is large.

<!-- Small modal -->
<div class="bg-white rounded-xl shadow-2xl w-full max-w-sm p-6">
  <p class="text-sm text-gray-700">Are you sure?</p>
  <div class="flex justify-end gap-3 mt-4">
    <button class="px-3 py-1.5 text-xs font-semibold border border-gray-300 rounded-lg">No</button>
    <button class="px-3 py-1.5 text-xs font-semibold text-white bg-red-600 rounded-lg">Yes, delete</button>
  </div>
</div>

ARIA Roles for Modal Accessibility

An accessible modal requires specific ARIA attributes. Add role='dialog' aria-modal='true' to the dialog panel so screen readers know it is a modal and that the rest of the page content is inert.

Link the dialog's title to the panel with aria-labelledby pointing to the heading's id. This allows screen readers to announce the dialog name when focus moves into it. For modals without a visible title, use aria-label on the dialog element directly.

<div
  role="dialog"
  aria-modal="true"
  aria-labelledby="dlg-title"
  class="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
  <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100">
    <h2 id="dlg-title" class="text-lg font-semibold text-gray-900">
      Confirm Deletion
    </h2>
    <button onclick="closeModal()" aria-label="Close dialog" class="p-1 text-gray-400 hover:text-gray-600 rounded-lg">&times;</button>
  </div>
  <div class="px-6 py-5">
    <p class="text-sm text-gray-600">This will permanently delete the selected item.</p>
  </div>
  <div class="flex justify-end gap-3 px-6 py-4 border-t border-gray-100">
    <button onclick="closeModal()" 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-red-600 rounded-lg">Delete</button>
  </div>
</div>

Putting the Full Modal Together

A complete modal implementation has two HTML sections: the backdrop and the centering container with the dialog panel inside. Both start hidden with hidden.

The trigger button is somewhere in the page content. When clicked, both elements are shown, body scroll is locked, and focus moves into the modal. When dismissed (button, backdrop, or Escape), both elements are hidden again and body scroll is restored.

<!-- Trigger -->
<button onclick="openModal()" class="px-4 py-2 bg-red-600 text-white text-sm font-semibold rounded-lg">Delete Account</button>

<!-- Backdrop -->
<div id="modal-backdrop" onclick="closeModal()"
     class="hidden fixed inset-0 bg-black/50 z-40"></div>

<!-- Dialog -->
<div id="modal" role="dialog" aria-modal="true" aria-labelledby="m-title"
     class="hidden fixed inset-0 flex items-center justify-center z-50 p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md">
    <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100">
      <h2 id="m-title" class="text-lg font-semibold text-gray-900">Delete Account</h2>
      <button onclick="closeModal()" aria-label="Close" class="p-1 text-gray-400 hover:text-gray-600 rounded">&times;</button>
    </div>
    <div class="px-6 py-5">
      <p class="text-sm text-gray-600">Are you sure? This cannot be undone.</p>
    </div>
    <div class="flex justify-end gap-3 px-6 py-4 border-t border-gray-100">
      <button onclick="closeModal()" 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-red-600 rounded-lg">Delete</button>
    </div>
  </div>
</div>

Quick Check

Test your understanding of Tailwind CSS Mastery concepts from this lesson.

Lesson Recap

In this lesson you learned: modal structure consists of a backdrop overlay (fixed inset-0 bg-black/50 z-40) and a centering container (fixed inset-0 flex items-center justify-center z-50) with the dialog panel inside; scrollable modals use flex flex-col max-h-[90vh] with flex-1 overflow-y-auto on the body; and ARIA attributes role='dialog' aria-modal='true' aria-labelledby are required for screen reader accessibility. Next up we animate modal open and close transitions.

자주 묻는 질문

“모달 대화상자 구조” 강의는 무료인가요?

네 — “모달 대화상자 구조” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“모달 대화상자 구조”에서 뭘 배우나요?

고정 위치 지정과 z-index 유틸리티를 사용해 배경 오버레이, 스크롤 가능한 콘텐츠 영역, 닫기 버튼이 있는 중앙 정렬 모달을 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“모달 대화상자 구조” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 모달 대화상자 구조
  2. 모달 열기 및 닫기 애니메이션
  3. 드롭다운 메뉴 컴포넌트
  4. 접근성을 고려한 모달과 드롭다운
← Tailwind CSS Academy(으)로 돌아가기