Overlay
Separates the temporary task from the page behind it.
Modals interrupt the page. Good modal CSS makes that interruption focused, accessible and easy to escape.
.modal { position: fixed; inset: 0; display: grid; place-items: center; }
.dialog { width: min(100%, 34rem); max-height: calc(100dvh - 2rem); overflow: auto; }
Component mental model
A modal creates a temporary task on top of the current page. That power should be used carefully.
Modal styling needs an overlay, a clear panel, a visible close action, controlled width, safe scroll behavior and strong focus styling.
The hard parts are not only visual. Focus management, escape behavior and background interaction must be handled by HTML and JavaScript too.
Separates the temporary task from the page behind it.
The focused panel where the task happens.
Users need an obvious way out.
Long modal content should not break mobile screens.
Visual model
The background becomes secondary.
The dialog contains one task.
The user can leave easily.
Long content stays usable.
Good CSS versus fragile CSS
.modal {
position: fixed;
inset: 0;
display: grid;
place-items: center;
padding: 1rem;
}
.dialog { width: min(100%, 34rem); max-height: calc(100dvh - 2rem); overflow: auto; }
.dialog {
position: absolute;
top: 120px;
left: 50%;
width: 900px;
}
Rules of thumb
A modal should cover the viewport consistently.
Dialogs should not become huge reading surfaces.
Use max-height and overflow for long content.
The escape route should not be hidden.
Interactive elements inside a modal still need focus-visible.
Do not use modals for ordinary page content.
Production thinking
A modal is a strong interruption. Good styling makes it feel intentional; bad styling makes it feel like a trap.
CSS is only part of modal accessibility. Focus trapping, aria, escape handling and background inertness need proper behavior too.
Test modals with keyboard only, long content, small screens and browser zoom.
Do not hide important indexable content only inside modals. Core content should remain available in the page.
Live code lab
The preview runs in an isolated iframe. Links and forms stay inside the practice area, so you can experiment without leaving the lesson.
Mini assignment
Practice assignment
Try it yourself
Self-check
Answer these questions before moving on. If a state, long label or mobile width breaks the component, the component is not finished yet.
Senior audit upgrade
CSS can style the overlay and panel. A real modal also needs focus management, escape behavior, background inertness and correct dialog semantics.
Keyboard focus should stay inside the modal while it is open.
Users expect Escape to close most non-destructive dialogs.
Use proper HTML and JavaScript behavior, not only a styled div.