CSS

CSS Grid: Overlay Elements within a Single Grid Cell

Discover how to elegantly overlay multiple elements, such as text on an image, using CSS Grid by placing them in the same grid cell for creative compositions.

.overlay-container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  width: 400px; /* Example size */
  height: 250px;
  border: 1px solid #ccc;
  overflow: hidden; /* Ensure content doesn't spill */
}

.overlay-item {
  grid-area: 1 / 1 / 2 / 2; /* Place all items in the first grid cell */
}

.overlay-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.overlay-text {
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 10px;
  align-self: end; /* Align text to bottom within the cell */
  z-index: 1; /* Ensure text is on top */
}
How it works: This snippet uses CSS Grid to overlay elements, such as text on an image. By assigning multiple child elements to the exact same grid cell using 'grid-area: 1 / 1 / 2 / 2;', they stack on top of each other. 'z-index' can control their stacking order, and properties like 'align-self' or 'justify-self' can position individual items within that shared cell, creating sophisticated layered designs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs