CSS

Overlay Elements in the Same Grid Cell with CSS Grid

Discover how to precisely stack and overlay multiple elements within a single grid area using CSS Grid, perfect for image captions, text over images, or layered effects.

.grid-container {
  display: grid;
  grid-template-areas: "overlay-area"; /* Define a single grid area */
  width: 400px; /* Example size */
  height: 250px; /* Example size */
  position: relative; /* For absolute positioning within if needed */
}

.item-background {
  grid-area: overlay-area; /* Assign to the defined area */
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 1;
}

.item-foreground {
  grid-area: overlay-area; /* Assign to the same area */
  z-index: 2; /* Ensure it appears on top */
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}
How it works: This technique leverages CSS Grid to place multiple items within the exact same grid cell, effectively stacking them. By defining a single `grid-template-areas` named 'overlay-area' on the container, both `.item-background` and `.item-foreground` are assigned to this area using `grid-area: overlay-area`. The `z-index` property then controls which element appears on top, allowing for powerful layering effects like text overlays on images.

Need help integrating this into your project?

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

Hire DigitalCodeLabs