← Back to category

Documentation

How to Center an Element with Flexbox

Centering that drifts when the width changes is usually still using a fixed margin. Flexbox calculates the leftover space. Edit in editor.clincoo.buzz and check the live preview.

Make the parent a flex container

Set display: flex on the wrapper, not on the child you want centered. justify-content: center moves along the main axis. align-items: center moves along the cross axis. Together they center the child in both directions.

Watch the axis direction

flex-direction: column swaps the axes. After column, justify-content controls the vertical axis and align-items controls the horizontal axis. If only one axis moved, check which property you changed.

Give the wrapper a height

align-items has no visible effect when the wrapper is only as tall as the child. For a hero, set a min-height, for example 60vh. Do not center with position absolute unless the element must leave normal flow.

Save the CSS, reload the preview, then narrow the width. If the text stays centered in one column, Flexbox is correct. Grid is a better fit when you are aligning several cells, not one box.