Center a div with Flexbox on the parent
fluency with Flexbox alignment axes.
set display flex on parent, justify-content center for the main axis, align-items center for the cross axis.
WHAT THIS TESTS A deceptively simple question that reveals whether you truly understand Flexbox's main-axis versus cross-axis model rather than memorizing a snippet.
A GOOD ANSWER COVERS Apply three declarations to the parent: display: flex turns it into a flex container; justify-content: center centers children along the main axis; align-items: center centers them along the cross axis. With the default flex-direction: row, the main axis is horizontal and the cross axis is vertical, so justify-content handles horizontal centering and align-items handles vertical. The inner div needs no positioning of its own. Note that vertical centering is only visible if the parent has height, whether from an explicit value, a min-height like 100vh, or being a flex item that stretches.
COMMON WRONG ANSWERS Swapping the two properties, saying justify-content centers vertically; that is only true if flex-direction is column, which flips the axes. Reaching for position: absolute with top/left 50% and transform translate, which works but ignores the constraint to use only Flexbox. Forgetting the parent needs a height, then claiming the technique does not center vertically.
LIKELY FOLLOW-UPS What changes with flex-direction: column? The axes flip, so justify-content now controls vertical and align-items controls horizontal. Difference between align-items and align-content? align-items aligns items on the cross axis within a single line; align-content distributes multiple wrapped lines. Is there a shorthand? place-content: center sets both justify-content and align-content at once, and place-items handles the items variant.
ONE CONCRETE EXAMPLE Given .outer { display: flex; justify-content: center; align-items: center; min-height: 100vh; } the inner .inner sits dead center of the viewport with no rules on the child itself. If you later set flex-direction: column on .outer, the centering still looks identical because both properties point at center, but the underlying axes have swapped, which is the conceptual point worth stating aloud.
Read the original → developer.mozilla.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.