How to Center a Div

Or how I learned to stop worrying and love flexbox

January 27, 2023

CSS has the uncanny ability of taking a simple idea and making it hard to implement. The question of how to center a div was the perfect example of this fact. But with the addition of flexbox, centering a div has become as simple as it sounds.

The Flex Approach

Here's how to center a div using flexbox. Given a div you want to center, assign the following attributes to its parent element:


display: flex;
justify-content: center;
align-items: center;
      

The justify-content attribute centers the div along the horizontal axis and align-items centers along the vertical axis. (It's slightly more complicated. If you're interested in the details of flexbox, I recommend this site.)

There are some scenarios where this won’t work perfectly, but the main idea stands. To center a div, simply add a couple of flex attributes to the parent.

A Complication

The flex approach will fail if the parent element contains other children, because changing the display attribute of the parent will affect every child. To center only the target div, create a new div between the parent and child. Then the flex approach will work as intended because the new parent div only has one child: the target div.

Also, you may have to increase the new parent div’s dimensions or else the target will be centered within a non-centered parent.