CSS
CSS Grid: Overlaying Elements within a Single Grid Cell
Learn to perfectly layer and position multiple elements on top of each other within a specific CSS Grid cell, ideal for image captions, interactive overlays, or complex component designs.
.grid-cell-overlay-container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
width: 400px;
height: 250px;
border: 1px solid #ccc;
}
.background-image {
grid-area: 1 / 1 / 2 / 2; /* Spans row 1, column 1 */
width: 100%;
height: 100%;
object-fit: cover;
}
.overlay-text {
grid-area: 1 / 1 / 2 / 2; /* Occupies the exact same cell */
position: relative; /* Or absolute for fine-tuning */
background-color: rgba(0, 0, 0, 0.5);
color: white;
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
/* Other grid items */
.grid-item-2 { grid-area: 1 / 2 / 2 / 3; background-color: lightblue; }
.grid-item-3 { grid-area: 2 / 1 / 3 / 2; background-color: lightgreen; }
.grid-item-4 { grid-area: 2 / 2 / 3 / 3; background-color: lightcoral; }
How it works: This snippet illustrates how to overlay elements within a single grid cell. By assigning multiple grid items to the exact same `grid-area` (e.g., `grid-area: 1 / 1 / 2 / 2`), they will occupy the same space. The stacking order is determined by their order in the HTML, with later elements appearing on top. You can then use `position: relative` or `position: absolute` on the overlaying element along with `z-index` if more precise control over positioning and stacking context is needed.