Axis Alignment
Overview
Once your Flex Main Axis is established, you need to distribute the empty space inside the container. You have two tools: justify-content (which aligns items along the Main Axis) and align-items (which aligns items along the perpendicular Cross Axis). These two properties are the absolute holy grail of modern UI spacing, allowing you to perfectly space out navigation links or center icons instantly.
Syntax
/* Assuming flex-direction: row (default) */
.nav-bar {
display: flex;
/* --- JUSTIFY-CONTENT (Main Axis / Horizontal here) --- */
justify-content: flex-start; /* Pack to the left */
justify-content: center; /* Pack in the dead center */
justify-content: space-between; /* Push first to left, last to right! */
justify-content: space-evenly; /* Perfectly equal gaps everywhere */
/* --- ALIGN-ITEMS (Cross Axis / Vertical here) --- */
align-items: stretch; /* Default: Items stretch to fill the height */
align-items: center; /* Vertically center the items */
align-items: flex-end; /* Push items to the bottom */
}Common Pitfalls
- Using
justify-content: space-betweenwhen you only have two items, but wanting them grouped together.space-betweenwill violently shove one item to the far left edge and the other to the far right edge. If you want them centered together with a gap, usejustify-content: centerwith agapproperty. - Trying to use
align-itemswithout setting aheighton the container. If the flex container doesn't have a defined height (e.g.,height: 100vh), it will just shrink-wrap its children. You cannot vertically align items if there is no vertical empty space to move them around in!
Interview Questions
align-items (on the parent) and align-self (on the child)?align-items sets the default Cross Axis alignment rule for EVERY child in the container. align-self is applied to a specific child, allowing it to override the parent's rule and align itself independently (e.g., one icon pushing itself to the bottom while the rest stay centered).
Real-World Example
Building the ubiquitous 'Logo on left, Nav Links on right' header.
.site-header {
display: flex;
/*
Pushes the Logo (Child 1) to the far left edge
and the Nav Group (Child 2) to the far right edge!
*/
justify-content: space-between;
/* Ensures the logo and links are perfectly centered vertically */
align-items: center;
}Check Your Knowledge
Test your understanding of Axis Alignment with these quick questions.