CSS
Robust Full-Viewport Modal Centering with CSS Grid
Achieve perfect, robust centering for modal dialogs or overlays within the entire viewport using CSS Grid, ensuring accessibility and responsiveness.
.overlay-container {
display: grid;
place-items: center; /* Shorthand for align-items: center and justify-items: center */
position: fixed; /* Fixes it to the viewport */
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.7); /* Semi-transparent background */
z-index: 1000; /* Ensure it's on top of other content */
/* Optional: Hide by default, show with JavaScript */
/* display: none; */
}
.modal-content {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
max-width: 90%; /* Responsive sizing */
max-height: 90vh; /* Responsive sizing */
overflow: auto; /* Enable scrolling if content exceeds height */
text-align: center; /* Center text inside modal */
}
How it works: This snippet provides a highly effective way to center a modal or overlay within the entire viewport using CSS Grid. The `.overlay-container` is set to `position: fixed` to cover the whole screen (`100vw`, `100vh`) and given a high `z-index`. `display: grid` combined with `place-items: center` (a shorthand for `align-items: center` and `justify-items: center`) ensures its child, the `.modal-content`, is perfectly centered both horizontally and vertically. `max-width` and `max-height` are used to make the modal responsive and prevent overflow, with `overflow: auto` allowing scrolling if content is too long.