A full-screen overlay

Build the backdrop for a pop-up message.

What to build

A dimmed overlay with a box in its centre.

Requirements

  • .overlay is fixed, with inset: 0.
  • .overlay has a background of black at 50% strength, and z-index: 100.
  • .overlay centres .box using flexbox.
  • .box has a background of white and a padding of 24px.

Constraints

Do not use opacity, because the box must stay solid. Do not use top and left to centre the box.

Example

position: fixed; inset: 0; covers the whole window.

Why it works

Fixed positioning attaches the overlay to the window, so that it still covers the page after scrolling, and flexbox looks after the centring. An alpha background darkens the page while leaving the box solid.

Hints

Hint 1

inset 0 stretches an element to all four edges.

Hint 2

A flex container centres the box.

Hint 3

The box goes above the page because the overlay is fixed and has a z-index.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Overlay</title>
  <style>
    .overlay {
      position: fixed;
      inset: 0;
      z-index: 100;
      background: rgb(0 0 0 / 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .box {
      background: white;
      padding: 24px;
    }
  </style>
</head>
<body>
  <p>The page underneath.</p>
  <div class="overlay">
    <div class="box">Are you sure?</div>
  </div>
</body>
</html>

Lesson: Positioning and stacking →