CSS

Position Content Over an Image or Element with CSS Grid

Create robust overlays for images or other elements by precisely positioning text, icons, or buttons directly on top using CSS Grid for exact alignment and layering.

.overlay-container {
  display: grid;
  position: relative; /* Needed if container has position: absolute for other elements */
  width: 100%;
  max-width: 500px;
  margin: 20px auto;
  border: 1px solid #ccc;
}

.overlay-container > * {
  grid-area: 1 / 1 / -1 / -1; /* All children occupy the same grid cell */
}

.background-image {
  width: 100%;
  height: auto;
  display: block;
}

.overlay-text {
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 10px 15px;
  justify-self: center; /* Horizontal alignment within the cell */
  align-self: end; /* Vertical alignment within the cell */
  margin-bottom: 20px; /* Add some space from the bottom */
  border-radius: 5px;
}
How it works: This powerful technique uses CSS Grid to easily layer and position elements on top of each other. By making the parent a `display: grid;` container and setting all its direct children to `grid-area: 1 / 1 / -1 / -1;`, every child occupies the exact same grid cell, effectively stacking them. This allows the `.background-image` to be at the bottom and `.overlay-text` (or any other content) to sit on top. `justify-self` and `align-self` are then used on the overlay element to precisely position it within that shared grid cell, offering flexible control for corners, centers, or edges.

Need help integrating this into your project?

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

Hire DigitalCodeLabs