Search code examples
reactjsdialogtailwind-css

Tailwind backdrop not applying to dialog element


I'm trying to add a backdrop behind a <dialog> in a React component in a NextJS app. I'm using Tailwind v3.3.2 and all my other styles are applying correctly, but the styles for backdrop:bg-gray-500 aren't applying any styles in the browser.

I've written a React component that renders the following:

      <dialog className="backdrop:bg-gray-50" open={true}>
        This is a dialog
      </dialog>

I would expect this to add a gray backdrop behind the element, but nothing is being applied to the element.

I've looked through the Tailwind docs and this looks like what I've tried: https://tailwindcss.com/docs/hover-focus-and-other-states#dialog-backdrops


Solution

  • There is no native backdrop element displayed when using the open attribute, as per the MDN documentation:

    If a <dialog> is opened using the open attribute, it will be non-modal.

    So to show the backdrop, we'd need to use the .showModal() method on the HTMLDialogElement JavaScript representation of the element, as per the MDN documentation:

    The ::backdrop CSS pseudo-element can be used to style the backdrop that is displayed behind a <dialog> element when the dialog is displayed with HTMLDialogElement.showModal().

    function App() {
      const dialog = React.useRef();
      
      React.useLayoutEffect(() => {
        dialog.current.showModal();
      }, [dialog]);
      
      return (
        <dialog className="backdrop:bg-gray-50" ref={dialog}>
          This is a dialog
        </dialog>
      );
    }
    ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    
    <div id="app"></div>
    
    Content