CSS

Overlay Text on an Image with CSS Grid

Learn an elegant method to position text directly over an image using CSS Grid by making elements occupy the same grid cell for stunning overlays.

.image-overlay-container {
  display: grid;
  grid-template-areas: "overlay";
  place-items: center; /* Center content vertically and horizontally */
  position: relative; /* If you need content outside the grid to reference this */
}

.image-overlay-container > * {
  grid-area: overlay;
}

.image-overlay-container img {
  width: 100%;
  height: auto;
  display: block;
}

.image-overlay-container .overlay-text {
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 1rem;
  border-radius: 5px;
  text-align: center;
  z-index: 1; /* Ensure text is above image */
}
How it works: This snippet uses CSS Grid to overlay text on an image. The parent container is set to `display: grid` and defines a single `grid-template-areas: "overlay"`. Both the `<img>` and the `.overlay-text` are assigned `grid-area: overlay`, causing them to stack in the same grid cell. `place-items: center` centers the content, and `z-index: 1` ensures the text appears above the image.

Need help integrating this into your project?

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

Hire DigitalCodeLabs