CSS

Overlay Elements with CSS Grid `grid-area`

Discover how to effortlessly overlay elements, create full-bleed sections, or build complex composite components using CSS Grid by assigning multiple items to the same `grid-area`.

.overlay-container {
  display: grid;
  grid-template-areas: "overlay-layer"; /* Define a single area */
  width: 400px;
  height: 250px;
  border: 2px solid #1d3557;
  position: relative; /* For z-index to work relative to stacking context */
  margin: 20px;
}

.background-image {
  grid-area: overlay-layer; /* Both elements occupy the same grid area */
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0.8;
  z-index: 1; /* Lower z-index for background */
}

.overlay-text {
  grid-area: overlay-layer; /* Both elements occupy the same grid area */
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 2em;
  font-weight: bold;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 2; /* Higher z-index for text to be on top */
  text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}

/* HTML Structure */
/*
<div class="overlay-container">
  <img class="background-image" src="https://picsum.photos/400/250" alt="Scenic background">
  <div class="overlay-text">
    <h1>Overlay Content</h1>
  </div>
</div>
*/
How it works: This snippet showcases a powerful CSS Grid technique for overlaying elements. By defining a single `grid-template-areas` named "overlay-layer" and assigning multiple grid items to that same `grid-area`, they are effectively stacked on top of each other. The `z-index` property is then used to control the stacking order, allowing one element (e.g., text) to appear on top of another (e.g., an image). This method provides a clean and semantic way to create complex overlays or full-bleed sections without relying on absolute positioning.

Need help integrating this into your project?

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

Hire DigitalCodeLabs