← Back to all snippets
CSS

Overlay Elements (Image with Text Caption) using CSS Grid

Learn to easily overlay one element perfectly on top of another, such as placing a text caption over an image, using the powerful positioning capabilities of CSS Grid for elegant and responsive designs.

.overlay-container {
  display: grid;
  grid-template-areas: "stack"; /* Defines a single grid area named "stack" */
  position: relative; /* Useful for z-index context, though grid handles stacking */
  width: 400px; /* Example fixed width */
  height: 250px; /* Example fixed height */
  overflow: hidden;
  border: 1px solid #ddd;
}

.overlay-container > * {
  grid-area: stack; /* Both children occupy the same grid area */
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* Ensures image covers the area */
  display: block; /* Remove extra space below image */
}

.caption {
  align-self: end; /* Aligns caption to the bottom of the grid area */
  justify-self: start; /* Aligns caption to the left of the grid area */
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 10px;
  width: 100%; /* Make caption span full width */
  box-sizing: border-box; /* Include padding in width */
  text-align: center;
}

/* HTML Context */
/*
<div class="overlay-container">
  <img src="https://via.placeholder.com/400x250/777/fff?text=Image" alt="Placeholder" class="image">
  <div class="caption">Beautiful Landscape</div>
</div>
*/
How it works: The `.overlay-container` is set to `display: grid` with `grid-template-areas: "stack"`. Both the `img` and `div.caption` children are assigned to `grid-area: stack`, causing them to occupy the exact same grid cell and effectively stack on top of each other. `align-self` and `justify-self` are then used on the `.caption` to position it within that shared cell, placing it at the bottom.

Need help integrating this into your project?

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

Hire DigitalCodeLabs