CSS

Overlay Elements with CSS Grid

Easily create complex layered effects or image/text overlays by positioning multiple elements in the same grid cell using CSS Grid, enabling powerful visual designs.

.overlay-container {
  display: grid;
  /* Define a single grid cell */
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  overflow: hidden; /* Hide anything outside the container */
  position: relative; /* Useful for general stacking context */
}

.background-image,
.overlay-text {
  grid-column: 1;
  grid-row: 1;
  /* Place both items in the same grid cell */
  width: 100%;
  height: 100%;
}

.background-image {
  object-fit: cover; /* Ensure image covers the area */
  z-index: 1;
}

.overlay-text {
  display: flex; /* For centering text within the overlay */
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent overlay */
  color: white;
  font-size: 1.5em;
  font-weight: bold;
  text-align: center;
  z-index: 2; /* Ensure text is above image */
}
How it works: This snippet shows how to overlay elements by placing them in the same grid cell. The `.overlay-container` is set to `display: grid` with a single column and row (`1fr`). By applying `grid-column: 1` and `grid-row: 1` to both the `.background-image` and `.overlay-text`, they are stacked in the exact same position. `z-index` is then used to control their visual stacking order, ensuring the text appears on top of the image.

Need help integrating this into your project?

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

Hire DigitalCodeLabs