CSS

Overlaying Content on Images with CSS Grid

Easily create stunning hero sections or image galleries with text overlays by leveraging CSS Grid's powerful stacking capabilities using explicit grid placement.

.image-overlay-container {
    display: grid;
    place-items: center; /* Center content both horizontally and vertically */
    position: relative; /* For z-index if needed, though not strictly required by grid for stacking */
}

.image-overlay-container > img,
.image-overlay-container > .overlay-content {
    grid-column: 1 / -1; /* Span all columns */
    grid-row: 1 / -1;    /* Span all rows */
}

.image-overlay-container > img {
    width: 100%;
    height: auto;
    display: block; /* Remove extra space below image */
    object-fit: cover; /* Ensure image covers the area */
}

.overlay-content {
    color: white;
    text-align: center;
    padding: 20px;
    background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent background */
    border-radius: 8px;
    z-index: 1; /* Ensure overlay is above the image */
    max-width: 80%; /* Constrain overlay width */
}

/* Example HTML structure */
/*
<div class="image-overlay-container">
    <img src="path/to/your/image.jpg" alt="Description">
    <div class="overlay-content">
        <h2>Stunning View</h2>
        <p>Explore beautiful landscapes.</p>
        <button>Learn More</button>
    </div>
</div>
*/
How it works: This snippet shows how to overlay text or other content on top of an image using CSS Grid. By placing both the image and the overlay content into the same `grid-column` and `grid-row` (`1 / -1`), they occupy the same space within the grid container, effectively stacking one on top of the other. `place-items: center` is used to center the overlay content, and a semi-transparent background provides readability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs