Tailwind backdrop not applying to dialog element – Dialog

by
Ali Hasan
mddialog reactjs tailwind-css

The Solutions:

Solution 1: Using HTMLDialogElement.showModal()

When using the `open` attribute on a <dialog> element, no native backdrop is displayed. To display the backdrop, we need to use the `.showModal()` method on the `HTMLDialogElement` JavaScript representation of the element.

Here’s a code example:

<!– begin snippet: js hide: false console: false babel: true –>

<!– language: lang-js –>

function App() {
const dialog = React.useRef();

React.useLayoutEffect(() => {
dialog.current.showModal();
}, [dialog]);

return (
<dialog className="backdrop:bg-gray-50" ref=>
This is a dialog
</dialog>
);
}
ReactDOM.createRoot(document.getElementById(‘app’)).render(<App/>);

<!– language: lang-html –>

<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

<!– end snippet –>

Q&A

Why is the Tailwind backdrop not applying to dialog element?

The backdrop will only display after the .showModal() method is used on the HTMLDialogElement JavaScript representation of the element.

How to fix issue with styling not applying to backdrop?

Use the showModal method to show the backdrop, and apply styles to the backdrop pseudo-element.

Video Explanation:

The following video, titled "Styling a Radix Dialog with Tailwind CSS - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Learn how to use Tailwind CSS to style a Radix UI Dialog component to match the look and feel of our app! This is Part 1 of a series in ...