Creating an Interactive Modal with Tailwind CSS: A Comprehensive Guide

Dan Gold

Written by Dan

Heads up, this content is in beta. Use at your own risk!

Modals, or dialog boxes, are common components in many web applications. They are used to grab user attention and gather input. In this guide, we’ll create a simple, yet stylish and responsive modal using Tailwind CSS.

Let’s start with the HTML structure of a basic modal:

<button class="px-4 py-2 font-bold text-white bg-blue-500 rounded show-modal">Show modal</button>

<div class="fixed inset-0 z-10 hidden overflow-y-auto modal">
    class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center"
      class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
    <span class="hidden sm:inline-block sm:align-middle sm:h-screen"></span
      class="inline-block px-4 pt-5 pb-4 overflow-hidden text-left align-bottom transition-all transform bg-white rounded-lg shadow-xl sm:align-middle sm:max-w-lg sm:w-full sm:p-6"
        <h3 class="text-lg font-medium leading-6 text-gray-900">Modal Title</h3>
        <div class="mt-2">
          <p class="text-sm text-gray-500">This is a simple modal example.</p>
      <div class="mt-5 sm:mt-6">
          class="inline-flex justify-center w-full px-4 py-2 text-base font-medium text-white bg-blue-600 border border-transparent rounded-md shadow-sm close-modal hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:text-sm"

  const body = document.querySelector('body');
  const modal = document.querySelector('.modal');
  const showModalButton = document.querySelector('.show-modal');
  const closeModalButton = document.querySelector('.close-modal');

  showModalButton.addEventListener('click', () => {

  closeModalButton.addEventListener('click', () => {

In this example, we’ve set up a basic modal with a title, a text paragraph, and a close button. It contains several elements to ensure it’s displayed correctly and smoothly:

  1. The outer div is fixed in the window, covers the whole screen (inset-0), and allows vertical scrolling (overflow-y-auto).
  2. The second div is a flex container centered both horizontally and vertically, with some padding applied.
  3. The third div represents the semi-transparent background overlay, which is also fixed and covers the whole screen.
  4. The span is a ghost element used to vertically center the modal for small screens.
  5. The fifth div is our actual modal. It has a white background (bg-white), rounded corners (rounded-lg), padding (px-4 pt-5 pb-4), text alignment (text-left), overflow hiding (overflow-hidden), and a shadow (shadow-xl). We also apply some responsive styles for larger screens with the sm: prefix.

Last updated

July 14th, 2023