CSS
Overlaying Elements with CSS Grid
Learn to precisely overlap and layer elements using CSS Grid, enabling complex UI designs like image overlays or text on backgrounds.
/* HTML Structure: */
/* <div class="overlay-container">
/* <img src="image.jpg" alt="Background Image" class="background-image">
/* <div class="overlay-content"><h1>Hello Grid!</h1><p>Text Overlay</p></div>
/* </div> */
.overlay-container {
display: grid;
/* Defines a single grid cell */
grid-template-columns: 1fr;
grid-template-rows: 1fr;
position: relative; /* Needed if children use absolute positioning for fine-tuning */
width: 100%;
height: 300px; /* Example fixed height */
overflow: hidden;
}
.background-image,
.overlay-content {
/* Both elements occupy the exact same grid cell, causing them to stack */
grid-column: 1 / -1; /* Spans from the first to the last column line */
grid-row: 1 / -1; /* Spans from the first to the last row line */
}
.background-image {
width: 100%;
height: 100%;
object-fit: cover; /* Ensures image covers the container */
}
.overlay-content {
z-index: 1; /* Ensures content is on top */
display: flex;
justify-content: center;
align-items: center;
color: white;
background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent background */
text-align: center;
}
How it works: This snippet demonstrates how to overlay elements using CSS Grid by placing them in the same grid cell. The `.overlay-container` is set to `display: grid;` and defines a single `1fr` column and `1fr` row, creating a single grid cell. Both the `.background-image` and `.overlay-content` children are then assigned to span this entire single cell using `grid-column: 1 / -1;` and `grid-row: 1 / -1;`. This causes them to stack on top of each other. `z-index` is used to control the stacking order, and `object-fit: cover` ensures the image scales correctly.