CSS
Grid Layering for Overlapping Content
Create sophisticated overlapping content layouts, like text on an image, by placing multiple grid items within the same grid cell using CSS Grid's powerful layering capabilities.
.overlay-container {
display: grid;
grid-template-columns: 1fr; /* A single column */
grid-template-rows: 1fr; /* A single row */
position: relative; /* Optional: for positioning children absolutely if needed */
width: 400px; /* Example size */
height: 250px;
overflow: hidden;
border: 1px solid #ccc;
}
.overlay-container > * {
grid-column: 1 / -1; /* Place all children in the first (and only) column */
grid-row: 1 / -1; /* Place all children in the first (and only) row */
}
.image {
width: 100%;
height: 100%;
object-fit: cover;
z-index: 1;
}
.text-overlay {
background-color: rgba(0, 0, 0, 0.6);
color: white;
padding: 1rem;
display: flex; /* Use flexbox for internal alignment of text */
align-items: center;
justify-content: center;
text-align: center;
z-index: 2; /* Ensure text is above image */
}
How it works: This snippet demonstrates how to achieve overlapping content, such as text on an image, using CSS Grid. By defining a single grid cell (e.g., `grid-template-columns: 1fr; grid-template-rows: 1fr;`) and then placing all child elements within that same cell using `grid-column: 1 / -1` and `grid-row: 1 / -1`, multiple items can be stacked. The `z-index` property is then used to control the layering order, ensuring the text overlay appears above the image. This technique is highly flexible for creating complex layered effects without resorting to absolute positioning for every element.