CSS

Overlaying Elements in a Single CSS Grid Cell

Master CSS Grid to create layered designs by placing multiple elements directly on top of each other within the same grid cell, perfect for badges or captions.

.grid-overlay-container {
  display: grid;
  grid-template-columns: 1fr; /* Defines a single column */
  grid-template-rows: 1fr;    /* Defines a single row */
  width: 350px;
  height: 220px;
  border: 2px solid #333;
  overflow: hidden;
}
.grid-overlay-item {
  grid-column: 1 / -1; /* Place in the first (and only) column */
  grid-row: 1 / -1;    /* Place in the first (and only) row */
  /* This effectively places all items into the same, single cell */
}
.background-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 1;
}
.overlay-text {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 1.3em;
  font-weight: bold;
  text-align: center;
  padding: 10px;
  z-index: 2;
  transition: background-color 0.3s ease;
}
.overlay-text:hover {
  background-color: rgba(0, 0, 0, 0.8);
}
How it works: This code illustrates how CSS Grid can be used to overlay elements. By assigning multiple grid items to the exact same grid cell (using `grid-column: 1 / -1;` and `grid-row: 1 / -1;` to span the entire single-cell grid), they stack on top of each other. The `z-index` property can then be used to control their visual stacking order, allowing for creative effects like image captions, badges, or interactive overlays on top of other content within a defined area.

Need help integrating this into your project?

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

Hire DigitalCodeLabs