CSS
Creating Overlapping Elements with CSS Grid Layering
Master CSS Grid to precisely position and stack elements on top of each other, enabling sophisticated and visually rich overlapping design patterns.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 columns for layout context */
grid-template-rows: repeat(2, 100px); /* 2 rows for layout context */
width: 400px;
height: 200px;
border: 2px solid #ccc;
margin: 20px;
position: relative; /* For absolute positioning context if needed for children, though grid itself handles overlap */
}
.item {
background-color: #a7d9f7;
border: 1px solid #3498db;
padding: 10px;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
}
.item-a {
grid-column: 1 / 3; /* Spans from column line 1 to 3 */
grid-row: 1 / 3; /* Spans from row line 1 to 3 */
background-color: #f0e68c; /* Lighter yellow */
z-index: 1; /* Bring forward */
}
.item-b {
grid-column: 2 / 4; /* Spans from column line 2 to 4 */
grid-row: 1 / 2; /* Stays in the first row */
background-color: #add8e6; /* Light blue */
z-index: 2; /* Overlaps item-a */
}
.item-c {
grid-column: 1 / 2; /* Stays in the first column */
grid-row: 2 / 3; /* Stays in the second row */
background-color: #90ee90; /* Light green */
z-index: 3; /* Overlaps item-a */
transform: translateX(20px); /* Just for visual flair */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Grid Overlap</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="grid-container">
<div class="item item-a">Item A (Background)</div>
<div class="item item-b">Item B (Overlap A)</div>
<div class="item item-c">Item C (Overlap A)</div>
</div>
</body>
</html>
How it works: This snippet shows how to create overlapping elements using CSS Grid. By defining a grid container with `display: grid`, child elements can be precisely placed and made to overlap using `grid-column` and `grid-row` properties. `grid-column: 1 / 3` means the item starts at grid line 1 and ends before grid line 3. When items occupy the same grid cells, they naturally overlap. The `z-index` property is then used to control the stacking order of these overlapping elements, bringing desired items to the foreground.