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. An infamous example of this is the challenge of centering a div. 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:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
By default, the justify-content attribute centers the div along the horizontal axis and align-items centers along the vertical axis.
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 is less simple when the parent element also contains other children. In this case, changing the parent also affects every other child. To get around this issue and only center the target div, create a new div between the parent and child. Then proceed with the flex approach which will center the target div only.
You may also have to increase the new parent div’s dimensions because the target might be centered within a non-centered parent.
Related
For more ways to center a div, here are some resources I've found to be informative.
- 11 Ways to Center Div or Text in Div in CSS by Jamie Juviler
- 5 Ways to Center a Div by Pradeep Pandey
And for more on flexbox, I highly recommend A Complete Guide to Flexbox by Chris Coyier.