Aligning Items in CSS (Flexbox & Grid)
CSS provides various alignment properties to control how elements are positioned within containers. Flexbox and Grid offer powerful tools to align items both horizontally and vertically.
1. Aligning Items in Flexbox
Flexbox uses justify-content
and align-items
to control alignment:
.flex-container {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
}
justify-content
: aligns items along the main axis (row or column).align-items
: aligns items along the cross axis.align-self
: overridesalign-items
for individual items.
2. Aligning Items in Grid
CSS Grid uses similar properties to control alignment:
.grid-container {
display: grid;
justify-items: center; /* aligns items horizontally */
align-items: center; /* aligns items vertically */
}
You can also align the whole grid content:
.grid-container {
justify-content: space-between;
align-content: center;
}
3. Aligning Individual Items
Use align-self
or justify-self
for specific item control:
.item {
align-self: flex-end;
justify-self: start;
}
4. Common Alignment Values
flex-start
/start
flex-end
/end
center
stretch
space-between
space-around
space-evenly
Conclusion
Whether you're using Flexbox or Grid, mastering alignment lets you create flexible, responsive, and visually balanced layouts. Start with container-level properties, and fine-tune individual elements as needed.