CSS
Precise Grid Item Placement and Overlapping with `grid-column` and `grid-row`
Master granular control over grid item positioning and intentional overlapping by directly specifying `grid-column` and `grid-row` start and end lines for complex designs.
.grid-container {
display: grid;
grid-template-columns: repeat(4, 1fr); /* 4 equal columns */
grid-template-rows: repeat(3, 100px); /* 3 fixed height rows */
gap: 10px;
width: 400px;
height: 300px;
margin: 30px auto;
border: 2px solid darkgreen;
position: relative; /* For z-index context */
}
.grid-item {
background-color: lightgreen;
border: 1px solid green;
padding: 10px;
text-align: center;
}
.item-1 {
grid-column: 1 / span 3;
grid-row: 1 / span 2;
background-color: #b0e0b0;
z-index: 1;
}
.item-2 {
grid-column: 3 / 5;
grid-row: 2 / 4;
background-color: #ffd700;
z-index: 2; /* Overlaps item-1 */
color: #333;
}
.item-3 {
grid-column: 1 / 2;
grid-row: 3 / 4;
background-color: #87ceeb;
}
How it works: CSS Grid provides precise control over item placement through `grid-column` and `grid-row` properties, which specify the starting and ending grid lines an item occupies. By defining explicit start and end lines, items can be positioned anywhere within the grid, including scenarios where they intentionally overlap. Using `span` allows an item to cover multiple tracks. When items overlap, the `z-index` property can be used to control their stacking order, enabling the creation of complex layered compositions within the grid structure without relying on `grid-template-areas`.