Center a Div with Flexbox justify-content and align-items

Center elements with flexbox

Flexbox centering uses justify-content and align-items instead of place-items. It's often preferred for dynamic content because flex items don't shrink below their content size when space is tight.

Old way 7 lines
/* Old approach: absolute positioning + transform */.parent {  position: relative;  height: 100%;}.child {  position: absolute;  top: 50%;  left: 50%;  transform: translate(-50%, -50%);}/* 5 declarations, 2 selectors, breaks on overflow */
3 lines
.parent   {  display: flex;  justify-content: center;  align-items: center;  height: 100%;}/* centered on both axes */
Widely available Since 2015 98% global usage

This feature is well established and works across many devices and browser versions. It has been available across browsers since 2015.

Safe to use without fallbacks.

29+
28+
9+
12+
Flexbox centers content and respects its size
Short text
This is much longer text that wraps

Left: content fits. Right: longer content wraps and stays readable. Flexbox respects content size.

Respects content size

Flex items won't shrink below their content. If content is wider than the container, it won't be clipped.

Dynamic content friendly

Better for items with variable widths, long text, or images. No height collapsing.

Explicit axes

justify-content (main) and align-items (cross) make the direction clear. Easier to reason about.

Modern Approach
display: flex
With justify-content and align-items
Best For
Dynamic content
When items vary in size

How it works

Flexbox centers using the main axis (justify-content) and cross axis (align-items). Center means the same in both directions: space is distributed equally on both sides.

The key difference from grid place-items: flex items won't shrink below their content size. If the centered element is wider than its container, it overflows gracefully instead of being clipped. This makes flexbox better for dynamic or unknown-size content.

Use flexbox when you're centering content that might grow, or when you need the explicit axis language (main vs. cross). Use grid place-items when you want both axes to behave identically with automatic shrinking.

ESC