Styling Dialog
Native dialog element with custom backdrop styling and entrance animation.
Dialog Structure
Native dialog element with modal behavior and inline close handler.
<dialog>
<h1>Styling Dialog</h1>
<p>This dialog is styled with CSS.</p>
<button onclick="this.closest('dialog').close()">Close</button>
</dialog>
Backdrop Customization
Use CSS custom properties for dialog-specific backdrop styling via inheritance.
:root {
/* Any ::backdrop can access this custom property */
--backdrop-color: #333;
}
dialog {
/* The ::backdrop for dialog can access this custom property */
--backdrop-color: rgba(0, 0, 0, 0.5);
}
::backdrop {
background-color: var(--backdrop-color);
}
Entrance Animation
Apply transition with @starting-style for smooth entrance effect on :open state.
dialog:open {
display: grid;
justify-items: center;
gap: 1rem;
padding: 1rem;
inset: 0;
margin: auto;
border-radius: 1rem;
opacity: 1;
translate: 0;
transition: opacity 0.3s ease, translate 0.3s ease;
@starting-style {
opacity: 0;
translate: 0 10%;
}
}
Modal Control
Simple event handlers for showModal() and close() methods.
const trigger = document.getElementById('trigger');
const dialog = document.querySelector('dialog');
const close = dialog.querySelector('button');
trigger.addEventListener('click', () => {
dialog.showModal()
});
close.addEventListener('click', () => {
dialog.close();
}); <main>
<button id="trigger">Open</button>
<dialog>
<h1>Styling Dialog</h1>
<p>This dialog is styled with CSS.</p>
<button onclick="this.closest('dialog').close()">Close</button>
</dialog>
</main>
<style>
main {
display: grid;
place-items: center;
height: 100vh;
}
button {
padding-block: 0.375rem;
padding-inline: 0.625rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 600;
color: #111827;
background-color: #ffffff;
cursor: pointer;
border-radius: 9999px;
border: 1px solid #363636;
&:hover {
background-color: #F9FAFB;
}
}
:root {
/* Any ::backdrop can access this custom property */
--backdrop-color: #333;
}
dialog {
/* The ::backdrop for dialog can access this custom property */
--backdrop-color: rgba(0, 0, 0, 0.5);
}
::backdrop {
background-color: var(--backdrop-color);
}
dialog:open {
display: grid;
justify-items: center;
gap: 1rem;
padding: 1rem;
inset: 0;
margin: auto;
border-radius: 1rem;
opacity: 1;
translate: 0;
transition: opacity 0.3s ease, translate 0.3s ease;
@starting-style {
opacity: 0;
translate: 0 10%;
}
}
dialog h1 {
margin: 0;
font-size: 1.5rem;
}
</style>
<script>
const trigger = document.getElementById('trigger');
const dialog = document.querySelector('dialog');
const close = dialog.querySelector('button');
trigger.addEventListener('click', () => {
dialog.showModal()
});
close.addEventListener('click', () => {
dialog.close();
});
</script>