CSS

Stack Multiple Items in a Single Grid Cell

Discover how to overlay elements precisely within the same CSS Grid cell, perfect for creating image captions, badges, or layered content using direct grid placement properties.

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 150px);
  gap: 10px;
  width: 100%;
  max-width: 600px;
  border: 1px solid #ccc;
  position: relative; /* For context if using absolute positioning within grid item */
}

.grid-item {
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2em;
}

.grid-item-overlap {
  grid-column: 2 / 3; /* Position in the second column */
  grid-row: 1 / 2;    /* Position in the first row */
  background-color: rgba(255, 0, 0, 0.5); /* Semi-transparent background */
  color: white;
  z-index: 2; /* Bring the overlay to the front */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.grid-item-base {
  grid-column: 2 / 3; /* Position in the second column */
  grid-row: 1 / 2;    /* Position in the first row */
  background-color: #aaddff; /* Background item */
  z-index: 1;
}

/* HTML Structure */
<!--
<div class="grid-container">
  <div class="grid-item">Cell 1</div>
  <div class="grid-item grid-item-base">Image or Base Content</div>
  <div class="grid-item">Cell 3</div>
  <div class="grid-item-overlap">Overlay Text or Badge</div>
  <div class="grid-item">Cell 5</div>
  <div class="grid-item">Cell 6</div>
</div>
-->
How it works: This snippet illustrates how to stack multiple elements within the same CSS Grid cell, creating layered content. By assigning identical `grid-column` and `grid-row` (or `grid-area`) values to different items, they will occupy the exact same grid cell. The `z-index` property then controls their stacking order, allowing you to place an 'overlay' item on top of a 'base' item. This technique is highly effective for design patterns like adding captions to images, placing badges on cards, or creating complex UI components where elements need to visually overlap within a defined grid space.

Need help integrating this into your project?

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

Hire DigitalCodeLabs