CSS
Overlay Content on Image using CSS Grid
Learn to elegantly layer text or other content directly over an image using CSS Grid for precise positioning and responsive behavior.
.image-overlay-container {
display: grid;
position: relative; /* Needed if content has position: absolute; */
place-items: center; /* Centers items if they don't span the whole grid */
}
.image-overlay-container img,
.image-overlay-container .overlay-content {
grid-area: 1 / 1 / 2 / 2; /* Both items occupy the same grid cell */
}
.image-overlay-container img {
width: 100%;
height: auto;
display: block;
}
.image-overlay-container .overlay-content {
color: white;
text-align: center;
padding: 1rem;
background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent background */
border-radius: 5px;
z-index: 1;
}
How it works: This snippet uses CSS Grid to overlay content on an image. By assigning both the `img` and `.overlay-content` to the same `grid-area` (`1 / 1 / 2 / 2`), they stack on top of each other. `place-items: center;` on the container ensures the overlay content is centered within that grid cell. The `z-index` on `.overlay-content` ensures it appears above the image, creating a clean overlay effect.