How to center a div with Flexbox
Center content on both axes with a small CSS example. Understand why container height, direction and available space matter.
For a simple centered panel, put display: flex on its parent, then set justify-content and align-items to center. Give the parent some space to work with.
.parent {
display: flex;
justify-content: center;
align-items: center;
min-height: 320px;
}Why these two properties?
With the default row direction in an English document, justify-content centers along the horizontal main axis. align-items centers across the vertical cross axis. Change the direction to column and those axes switch.
Why does vertical centering sometimes look broken?
If the parent is only as tall as the child, there is no extra vertical space to distribute. A minimum height makes the effect visible in this example. Choose a height or minimum height that fits your actual component, rather than copying 320px into every layout.
Try the controls instead of guessing
Open a centered layout in the interactive lab ↗. Switch between row and column, then change one alignment property at a time. The generated CSS updates with the preview.
Centering several items
Add a gap to separate the children. If the group can outgrow the container, consider wrapping and test a narrow width. Centering is not a substitute for checking what happens when the content becomes larger.
Center three items, then make a vertical stack without changing their order. Copy the CSS and try it in the lesson editor.
Further reference: MDN Web Docs ↗
Try the editable example ↗