Alignment and justification
Definition and purpose
Alignment positions flex items within their line and distributes extra space. The property to choose depends on the axis and whether you are positioning items or whole lines.
Center on both axes
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: flex; height: 100px; justify-content: center; align-items: center; } #p > div { width: 60px; height: 20px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>The group is centered horizontally and each item vertically.
Syntax and mental model
justify-content distributes main-axis space after flex sizing and auto margins. align-items controls cross-axis placement within a line; align-self overrides it for one item. align-content distributes cross-axis space across lines in a multi-line container.
Pack lines at end
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: flex; flex-wrap: wrap; height: 100px; align-content: flex-end; } #p > div { flex: 0 0 140px; height: 20px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>Two 20px lines occupy the last 40px.
Common mistakes
Do not use align-content to center items in an ordinary nowrap row. Also, if growing items consume all free space, justify-content has no positive space left to distribute.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Wrapping and gaps. Next lesson: Basis, grow and shrink.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Alignment and justification — knowledge check
Five questions on alignment and justification.
Which property distributes remaining main-axis space?
Which overrides cross-axis item alignment for one item?
What aligns multiple flex lines across the cross axis?
With three 60px boxes in a 300px row centered as a group, what is the first left offset?
What if flex growth consumes all positive free space?