CSS

Overlay Content with Grid Areas (Image Text Overlay)

Learn to precisely layer content, such as text over an image, using CSS Grid Areas, allowing for simple yet powerful positioning and responsive design.

.image-overlay-container {
  display: grid;
  grid-template-areas: "overlap"; /* Define a single grid area named 'overlap' */
  width: 100%;
  max-width: 400px;
  margin: 20px auto;
  position: relative; /* Needed for positioning relative to container if not grid-area */
  overflow: hidden;   /* Ensures content doesn't spill out */
  border: 1px solid #ccc;
}

.image-overlay-container > img {
  grid-area: overlap; /* Both image and text occupy the same grid area */
  width: 100%;
  height: auto;
  display: block; /* Remove extra space below image */
}

.overlay-text {
  grid-area: overlap; /* Both image and text occupy the same grid area */
  align-self: center; /* Vertically center the text within the grid area */
  justify-self: center; /* Horizontally center the text within the grid area */
  color: white;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 10px 20px;
  font-size: 1.2em;
  text-align: center;
}
How it works: This snippet demonstrates how to overlay content, like text on an image, using CSS Grid Areas. By defining a single grid area named `"overlap"` and assigning both the `img` and `.overlay-text` to `grid-area: overlap`, they are stacked directly on top of each other. `align-self` and `justify-self` are then used on the overlay text to precisely position it within that shared grid cell, creating a clean and responsive 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