0

How to Center a Div in CSS (Flexbox)

Build a CSS flexbox layout visually: flex-direction, justify-content, align-items, flex-wrap and gap on the container, plus per-child flex-grow, flex-shrink and flex-basis, all with a live preview and copyable CSS.

Processing... 0%

Result

Here is the direct answer to the most-asked question in CSS: to center a div, put display: flex, justify-content: center and align-items: center on its parent. That's it — three declarations on the container, and the child sits perfectly centered both horizontally and vertically inside it, at any size. This page opens the generator with exactly that combination already applied, so the preview below shows it working on three numbered boxes right now.

Before flexbox, centering a div needed hacks: margin: 0 auto only centered horizontally and only worked on a fixed-width block; vertical centering meant position: absolute with negative margins or a transform trick, both fragile the moment content changed size. justify-content handles the main axis and align-items handles the cross axis — together they center in both directions regardless of how tall or wide the child is, which is exactly why this pair became the standard answer.

Drag any control below and watch the three preview boxes stay centered as the container changes shape, or add a gap between them. When it looks right, copy the CSS block at the bottom straight into your stylesheet — it runs the same way in every modern browser, no library needed.