CSS
Create a Centered Full-screen Overlay or Modal with CSS Grid
Implement a perfectly centered, full-screen overlay or modal with a blurred background using CSS Grid, ideal for alerts, lightboxes, or dynamic content display.
.overlay-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6); /* Semi-transparent black background */
backdrop-filter: blur(5px); /* Optional: blur background content */
display: grid; /* Use Grid for centering */
place-items: center; /* Centers content both horizontally and vertically */
z-index: 1000; /* Ensure it's on top of other content */
/* Optionally hide/show with visibility: hidden; opacity: 0; transition: all 0.3s; */
}
.modal-content {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
max-width: 500px;
text-align: center;
}
.close-button {
margin-top: 20px;
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
<!-- HTML Structure -->
<button onclick="document.querySelector('.overlay-container').style.display = 'grid'">Open Modal</button>
<div class="overlay-container" style="display: none;">
<div class="modal-content">
<h2>Welcome to the Modal!</h2>
<p>This is a perfectly centered modal window.</p>
<button class="close-button" onclick="document.querySelector('.overlay-container').style.display = 'none'">Close</button>
</div>
</div>
How it works: This snippet creates a full-screen overlay (like a modal) that is perfectly centered using CSS Grid. The `overlay-container` is `position: fixed` to cover the entire viewport. By applying `display: grid` and `place-items: center`, its direct child (`.modal-content`) is automatically centered both horizontally and vertically within the overlay, providing a clean and responsive modal solution. `backdrop-filter` is added for an optional modern blur effect.