CSS
CSS Grid Layering Elements in a Single Cell
Achieve complex layered designs by placing multiple elements precisely within one grid cell using CSS Grid's implicit placement and `z-index`.
.layered-card {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
position: relative; /* For z-index to work reliably */
width: 300px;
height: 200px;
border: 1px solid #ccc;
overflow: hidden;
}
.card-image,
.card-badge {
grid-area: 1 / 1 / -1 / -1; /* Occupy the entire single grid cell */
position: relative; /* Ensure z-index works within grid context */
}
.card-image {
width: 100%;
height: 100%;
object-fit: cover;
z-index: 1;
}
.card-badge {
background-color: red;
color: white;
padding: 5px 10px;
border-radius: 5px;
position: absolute;
top: 10px;
right: 10px;
z-index: 2;
font-size: 0.8em;
}
How it works: This snippet demonstrates how to layer multiple elements within a single CSS Grid cell. The `.layered-card` is a grid container with a single column and row (`1fr` each). Both `.card-image` and `.card-badge` children are then explicitly placed into the same grid cell using `grid-area: 1 / 1 / -1 / -1`. By giving them `position: relative` (or `absolute` for `.card-badge` for finer positioning) and applying `z-index` values, their stacking order can be controlled, allowing the badge to appear over the image.