CSS

Full-Page Overlay/Modal Centering with Grid

Achieve perfect full-page overlay or modal centering using CSS Grid's `place-items` property, ensuring content is always centered, regardless of its size or screen dimensions.

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

.overlay.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: 90%;
  max-height: 90%;
  overflow: auto;
}
How it works: This CSS Grid snippet creates a full-page overlay that centers its content both horizontally and vertically. The `.overlay` element is absolutely positioned to cover the entire viewport. Setting `display: grid` on the overlay and then using `place-items: center` (a shorthand for `align-items: center` and `justify-items: center`) ensures that any direct child of the overlay, like the `.modal-content`, is perfectly centered within it. Transitions are added for a smooth show/hide effect.

Need help integrating this into your project?

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

Hire DigitalCodeLabs