CSS
Precisely Position Individual Grid Items with `justify-self` and `align-self`
Master `justify-self` and `align-self` in CSS Grid to gain granular control over the alignment of single items within their own grid cells, overriding container-level settings.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 100px); /* 3 columns, each 100px wide */
grid-template-rows: repeat(2, 80px); /* 2 rows, each 80px high */
gap: 10px;
border: 2px solid #333;
width: 350px; /* Example container width */
height: 200px; /* Example container height */
}
.grid-item {
background-color: #cfe2f3;
border: 1px solid #a4c2f4;
display: flex; /* For illustrative purposes of content within item */
justify-content: center;
align-items: center;
font-size: 0.9em;
}
.item-1 { /* Default alignment inherited from container or start */
justify-self: start;
align-self: start;
}
.item-2 {
justify-self: end;
align-self: end;
}
.item-3 {
justify-self: center;
align-self: center;
}
.item-4 {
justify-self: stretch;
align-self: stretch;
}
.item-5 {
justify-self: start;
align-self: center;
}
.item-6 {
justify-self: end;
align-self: stretch;
}
How it works: `justify-self` and `align-self` properties allow you to control the horizontal (inline axis) and vertical (block axis) alignment, respectively, of a single grid item within its own grid cell. While `justify-items` and `align-items` apply to all items in a container, these `self` properties enable fine-grained control over individual items. This is particularly useful when you need to override the container's default alignment for a specific item, or when a grid item occupies a larger grid area and needs precise positioning within that space.