← Back to all snippets
CSS

Stacking and Overlaying Elements with CSS Grid

Learn to elegantly stack and overlay multiple elements within the same grid cell, perfect for captions, badges, or complex layered designs.

.overlay-container {
  display: grid;
  /* Ensures there's a single, shared grid cell for all children */
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  position: relative; /* For absolute positioning of children if needed */
  width: 300px; /* Example size */
  height: 200px;
  border: 2px solid #3f51b5;
  overflow: hidden;
}

.item-background, .item-overlay-text, .item-badge {
  /* All items occupy the first column and first row, effectively stacking them */
  grid-column: 1 / -1;
  grid-row: 1 / -1;
  padding: 10px;
}

.item-background {
  background-color: #e8eaf6;
  z-index: 0; /* Base layer */
  display: flex; /* Example: to center content within this item */
  justify-content: center;
  align-items: center;
}

.item-overlay-text {
  background-color: rgba(63, 81, 181, 0.7);
  color: white;
  font-size: 1.2em;
  z-index: 1; /* Above background */
  display: flex;
  justify-content: center;
  align-items: center;
}

.item-badge {
  background-color: #ff5722;
  color: white;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute; /* Allows precise placement within the container */
  top: 10px;
  right: 10px;
  z-index: 2; /* On top of everything */
}
How it works: This snippet illustrates how to stack and overlay elements precisely using CSS Grid. By defining a grid with a single column (`grid-template-columns: 1fr;`) and a single row (`grid-template-rows: 1fr;`), and then having all child elements occupy that same grid cell using `grid-column: 1 / -1;` and `grid-row: 1 / -1;`, they are effectively layered on top of each other. The `z-index` property then controls their vertical stacking order, allowing you to determine which element appears on top. Combining this with `position: absolute;` on children gives even finer control over their placement within the shared grid cell.

Need help integrating this into your project?

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

Hire DigitalCodeLabs