CSS

Creating an Overlay or Modal Centered with Grid

Implement a perfectly centered modal or overlay component over your content using CSS Grid, ensuring it remains centered and responsive across different screen sizes with minimal code.

.overlay-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent background */
  display: grid;
  place-items: center;
  z-index: 1000;
  visibility: hidden; /* Hidden by default */
  opacity: 0;
  transition: visibility 0s, opacity 0.3s ease;
}

.overlay-container.active {
  visibility: visible;
  opacity: 1;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  max-width: 500px;
  text-align: center;
  transform: scale(0.9);
  transition: transform 0.3s ease;
}

.overlay-container.active .modal-content {
  transform: scale(1);
}
/* Example JS to toggle: document.querySelector('.overlay-container').classList.toggle('active'); */
How it works: This snippet provides a robust way to create a full-viewport overlay or modal. `position: fixed` along with `top: 0`, `left: 0`, `width: 100%`, and `height: 100%` ensures the container spans the entire screen. By setting `display: grid` and `place-items: center`, its direct child (`.modal-content`) is perfectly centered within the viewport. `visibility`, `opacity`, and `transform` properties are used to implement smooth show and hide transitions for a better user experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs