CSS

Overlaying Content on Images or Videos with CSS Grid

Learn to precisely position text or other content over an image or video background using a simple yet powerful CSS Grid layout technique for clean overlays.

.overlay-container {
    display: grid;
    position: relative; /* Needed for positioning if not using grid for absolute */
    width: 100%;
    max-width: 600px;
    margin: auto;
    border: 2px solid #007bff;
}

.overlay-container > * {
    grid-column: 1 / -1; /* All children span all columns */
    grid-row: 1 / -1;    /* All children span all rows */
}

.background-image {
    width: 100%;
    height: auto;
    display: block; /* Remove extra space below image */
}

.overlay-content {
    /* Align content within the grid cell */
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    color: white;
    background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent background */
    padding: 20px;
    font-size: 1.5em;
}

/* Example HTML structure for context:
<div class="overlay-container">
    <img class="background-image" src="your-image.jpg" alt="Background">
    <div class="overlay-content">
        <h1>Overlay Title</h1>
        <p>Some descriptive text here.</p>
    </div>
</div>
*/
How it works: This snippet demonstrates a clean way to overlay content (like text) on top of an image or video using CSS Grid. By making the parent container a `display: grid` and having all its direct children (`.overlay-container > *`) occupy the *exact same grid cell* (`grid-column: 1 / -1; grid-row: 1 / -1;`), the elements are stacked on top of each other. The content element can then be further styled (e.g., using Flexbox within itself) to position its own content, creating a perfect overlay effect.

Need help integrating this into your project?

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

Hire DigitalCodeLabs