CSS
Overlaying Text and Elements on an Image with CSS Grid
Learn how to elegantly overlay text, buttons, or other elements precisely on top of an image using the powerful stacking capabilities of CSS Grid.
.image-overlay-container {
display: grid;
position: relative; /* Establish positioning context for absolute children if needed */
max-width: 600px; /* Example max width */
margin: 0 auto;
}
.image-overlay-container img {
grid-area: 1 / 1 / 2 / 2; /* Place image in the first (and only) grid cell */
width: 100%;
height: auto;
display: block; /* Remove extra space below image */
z-index: 1; /* Ensure image is behind overlay content */
}
.image-overlay-content {
grid-area: 1 / 1 / 2 / 2; /* Place content in the same grid cell as image */
z-index: 2; /* Ensure content is on top of image */
/* Center the content horizontally and vertically */
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: white;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
padding: 20px;
text-align: center;
}
/* Example content styling */
.image-overlay-content h2 {
margin-bottom: 10px;
}
.image-overlay-content button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
margin-top: 15px;
}
How it works: This snippet demonstrates a powerful technique to overlay text or other elements precisely on top of an image using CSS Grid. Both the `<img>` and the `.image-overlay-content` are assigned to the exact same `grid-area: 1 / 1 / 2 / 2;`. This causes them to stack perfectly on top of each other. `z-index` is used to control which element appears on top. Inside the `.image-overlay-content`, Flexbox is used to easily center the overlay text and buttons. This method provides robust control over layering without relying on absolute positioning relative to the image parent.