CSS
Overlapping Grid Items for Stacking Effects
Create sophisticated stacking or overlay effects by making multiple CSS Grid items occupy the same grid cells, enabling easy layering of content, images, or interactive elements.
.stacking-container {
display: grid;
/* Define a single grid cell or a common area for overlap */
grid-template-columns: 1fr;
grid-template-rows: 1fr;
width: 300px;
height: 200px;
border: 2px solid #3498db;
position: relative; /* Often useful for z-index, though grid handles basic stacking */
}
.base-item, .overlay-item {
grid-column: 1 / -1; /* Span all columns (in this case, just one) */
grid-row: 1 / -1; /* Span all rows (in this case, just one) */
padding: 20px;
display: flex; /* Centering content within the item */
justify-content: center;
align-items: center;
}
.base-item {
background-color: #e0f2f7;
z-index: 1; /* Lower layer */
}
.overlay-item {
background-color: rgba(255, 165, 0, 0.7); /* Semi-transparent orange */
color: white;
z-index: 2; /* Higher layer */
font-weight: bold;
}
How it works: This snippet shows how to create stacking or overlapping effects using CSS Grid. By setting `grid-column: 1 / -1` and `grid-row: 1 / -1` for both `.base-item` and `.overlay-item`, they are both forced to occupy the exact same grid cells. The `z-index` property is then used to control the stacking order, allowing one item to appear on top of another. This is useful for creating effects like image captions, interactive overlays, or complex component arrangements within a structured grid.