CSS
Full-Screen Overlay/Modal Backdrop with Centered Content using CSS Grid
Learn to create a robust, full-screen overlay or modal backdrop that precisely centers its content using the power and simplicity of CSS Grid for perfect positioning.
.modal-overlay {
display: grid;
place-items: center; /* Centers content horizontally and vertically */
position: fixed; /* Fixed to viewport */
top: 0;
left: 0;
width: 100vw; /* Full viewport width */
height: 100vh; /* Full viewport height */
background-color: rgba(0, 0, 0, 0.7); /* Semi-transparent background */
z-index: 999; /* Ensure it's on top */
visibility: hidden; /* Hidden by default */
opacity: 0;
transition: visibility 0.3s, opacity 0.3s;
}
.modal-overlay.active {
visibility: visible;
opacity: 1;
}
.modal-content {
background-color: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
max-width: 500px; /* Limit modal width */
width: 90%; /* Responsive width */
text-align: center;
}
.modal-trigger-button {
padding: 10px 20px;
font-size: 1rem;
cursor: pointer;
}
/* <!-- HTML STRUCTURE --> */
<button class="modal-trigger-button" onclick="document.querySelector('.modal-overlay').classList.add('active')">Open Modal</button>
<div class="modal-overlay" onclick="if(event.target === this) this.classList.remove('active')">
<div class="modal-content">
<h2>Welcome to the Modal!</h2>
<p>This is some content inside the modal. It's perfectly centered using CSS Grid.</p>
<button onclick="document.querySelector('.modal-overlay').classList.remove('active')">Close Modal</button>
</div>
</div>
How it works: This snippet creates a full-screen overlay or modal backdrop using CSS Grid. The `.modal-overlay` is set to `position: fixed`, spanning the entire viewport (`100vw`, `100vh`). `display: grid` combined with `place-items: center` is a powerful and concise way to perfectly center any child content (`.modal-content`) both horizontally and vertically within the overlay. Transitions are added for a smooth fade-in/out effect when toggling the `active` class.