CSS
Overlay Elements by Stacking with CSS Grid
Create effective overlay effects, like placing text over an image or a modal over content, by stacking multiple elements in the same grid cell.
.stack-container {
display: grid;
grid-template-areas: "stack"; /* Define a single named grid area */
width: 100%;
max-width: 600px;
margin: 20px auto;
border: 1px solid #ccc;
overflow: hidden;
position: relative; /* Useful for positioning children relative to container */
}
.stack-container > * {
grid-area: stack; /* All direct children occupy the same grid area */
}
.background-image {
width: 100%;
height: auto;
display: block;
z-index: 1;
}
.overlay-text {
z-index: 2;
display: flex;
justify-content: center;
align-items: center;
color: white;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
font-size: 2em;
padding: 20px;
text-align: center;
}
How it works: This snippet uses CSS Grid to stack elements on top of each other, ideal for overlays or hero sections. By defining a single `grid-template-areas: "stack";` and then assigning all direct children to `grid-area: stack;`, every child element is placed in the exact same grid cell. This effectively stacks them one over another. The `z-index` property can then be used on the child elements to control their rendering order, allowing elements like text to appear clearly over an image or other background.