CSS

Centering a Modal or Overlay with Flexbox

Effortlessly center modal dialogs or full-screen overlays on any device by leveraging CSS Flexbox, ensuring optimal visibility and user experience.

.modal-overlay {
  position: fixed; /* Stays in place relative to the viewport */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6); /* Semi-transparent background */
  display: flex;
  justify-content: center; /* Centers content horizontally */
  align-items: center;     /* Centers content vertically */
  z-index: 1000;           /* Ensures it's on top of other content */
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.25);
  max-width: 500px;
  min-width: 300px;
  text-align: center;
}
How it works: This snippet illustrates how to create a perfectly centered modal or full-screen overlay using CSS Flexbox. The `.modal-overlay` is positioned `fixed` to cover the entire viewport (`top: 0; left: 0; width: 100%; height: 100%`). By applying `display: flex`, `justify-content: center`, and `align-items: center` to this overlay, its child element (`.modal-content`) is automatically centered both horizontally and vertically within the screen. The `z-index` ensures the overlay appears above other page content, creating a clean and user-friendly modal experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs