Why does align-items center not center my flex items horizontally?
Quick answer
align-items centers flex items on the cross axis, not automatically from left to right. With the usual flex-direction: row, the main axis is horizontal, so use justify-content: center for horizontal centering and align-items: center for vertical centering. With flex-direction: column, those axis directions swap, so align-items: center centers items horizontally. [S1]
The question, the details, the next step.
A practical checklist
Find the element that is the flex container and confirm it uses
display: flex.Read its
flex-direction:roworcolumn.Name the direction you want to center: horizontal or vertical.
Use
justify-contentfor the main axis andalign-itemsfor the cross axis.Recheck the result after changing
flex-direction, because the axis directions change.
A few more useful answers
In a row layout, which property centers items horizontally?
justify-content: center centers along the horizontal main axis when flex-direction: row. [S1]
Does `align-items: center` ever center items horizontally?
Yes. In a column layout, the cross axis is horizontal, so align-items: center centers along it. [S1]
What is the quickest way to remember the difference?
Find the main axis from flex-direction: justify-content controls that axis, and align-items controls the perpendicular cross axis. [S1]
Sources
References used for this guide.
- [S1] Basic concepts of flexbox - CSS | MDN developer.mozilla.org · Checked
