CSS
CSS Grid: Overlay and Stack Elements Precisely
Learn to stack multiple elements on top of each other within a CSS Grid layout using precise column and row placement for creating overlays, image captions, or complex designs.
<div class="grid-overlay-container">
<img src="https://via.placeholder.com/400x200?text=Background" alt="Background Image" class="overlay-item">
<div class="overlay-item overlay-text">
<h3>Overlay Title</h3>
<p>This text overlays the image.</p>
</div>
</div>
.grid-overlay-container {
display: grid;
width: 400px;
height: 200px;
border: 1px solid #ccc;
}
.overlay-item {
grid-column: 1 / -1; /* Span across all columns */
grid-row: 1 / -1; /* Span across all rows */
/* Specific styling for overlay text */
background-color: rgba(0, 0, 0, 0.5);
color: white;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
}
.overlay-item.overlay-text {
/* Ensure text is above image, if needed, though order in HTML matters too */
z-index: 1;
}
.grid-overlay-container img {
width: 100%;
height: 100%;
object-fit: cover;
}
How it works: This snippet demonstrates how CSS Grid can be used to overlay elements. By placing multiple child items within the same grid area (using `grid-column: 1 / -1` and `grid-row: 1 / -1`), they stack on top of each other. The order in the HTML determines the stacking context by default, but `z-index` can be used for explicit control. This technique is useful for creating image captions, hero sections with text overlays, or complex layered designs.