CSS
Align Individual Grid Items with `align-self` and `justify-self`
Discover how to precisely position specific items within a CSS Grid layout using `align-self` for vertical alignment and `justify-self` for horizontal alignment, overriding container defaults.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 100px);
gap: 10px;
background-color: #f0f8ff;
padding: 10px;
}
.grid-item {
background-color: #87ceeb;
border: 1px solid #4682b4;
display: flex; /* For content centering within item if needed */
justify-content: center;
align-items: center;
}
.item-start-end {
align-self: start; /* Aligns item to the top of its grid cell */
justify-self: end; /* Aligns item to the right of its grid cell */
background-color: #ffb6c1;
}
.item-center-stretch {
align-self: center; /* Centers item vertically */
justify-self: stretch; /* Stretches item horizontally */
background-color: #98fb98;
}
How it works: This snippet showcases how to control the alignment of individual grid items independently using `align-self` and `justify-self`. While `align-items` and `justify-items` apply to all items in a container, these 'self' properties allow specific items to override the container's alignment along the cross (vertical) and main (horizontal) axes respectively, enabling highly customized layouts.