CSS

Grid Overlay for Text on Images

Learn to perfectly overlay text or other elements on top of an image using CSS Grid, creating captivating visual effects effortlessly.

.image-container {
  display: grid;
  position: relative; /* Optional, for z-index context if needed */
}

.image-container > img {
  grid-column: 1 / -1; /* Spans all columns */
  grid-row: 1 / -1;    /* Spans all rows */
  width: 100%;
  height: auto;
  display: block;
}

.image-container > .overlay-text {
  grid-column: 1 / -1; /* Places text in the same grid area as image */
  grid-row: 1 / -1;
  z-index: 1; /* Ensures text is on top */
  display: flex; /* Use flex to center text within the overlay */
  justify-content: center;
  align-items: center;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 10px;
  text-align: center;
}
How it works: This snippet illustrates how to overlay elements using CSS Grid. By placing both the image and the overlay content into the same grid cell (using `grid-column: 1 / -1` and `grid-row: 1 / -1`), they effectively stack on top of each other. The `z-index` property ensures the overlay text appears above the image. Flexbox is then used within the `.overlay-text` to center the text content horizontally and vertically.

Need help integrating this into your project?

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

Hire DigitalCodeLabs