CSS
Fine-Tuning Item Placement Within CSS Grid Cells
Precisely control the alignment of individual items within their respective CSS Grid cells using `justify-self` and `align-self` properties for detailed layouts.
.grid-parent {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(2, 100px);
gap: 10px;
border: 1px solid #ccc;
padding: 10px;
font-family: sans-serif;
}
.grid-item {
background-color: lightcoral;
padding: 5px;
display: flex; /* For illustrative inner content centering */
justify-content: center;
align-items: center;
color: white;
border-radius: 4px;
font-weight: bold;
}
.grid-item:nth-child(1) {
justify-self: start; /* Aligns item to the start of its cell horizontally */
align-self: start; /* Aligns item to the start of its cell vertically */
}
.grid-item:nth-child(2) {
justify-self: end;
align-self: center;
}
.grid-item:nth-child(3) {
justify-self: center;
align-self: end;
}
.grid-item:nth-child(4) {
justify-self: stretch; /* Stretches item to fill its cell horizontally */
align-self: stretch; /* Stretches item to fill its cell vertically */
background-color: lightgreen;
color: #333;
}
How it works: This snippet illustrates how `justify-self` and `align-self` provide granular control over the placement of individual items within their designated CSS Grid cells. `justify-self` positions an item along the inline (horizontal) axis, and `align-self` along the block (vertical) axis. These properties allow values like `start`, `end`, `center`, and `stretch` to override the default alignment set by the parent grid container, enabling precise adjustments for specific elements in complex grid layouts.