5 Ways to center a <div>

The Document Structure:

We have two divs, a 'parent' and a 'child'. We will work on centering 'child' — both vertically and horizontally — with respect to 'parent'.

image.png

1. Using Flexbox

Flexbox has made centering a div (and virtually anything) easy as hell.

We use the 'justify-content' property to center the 'child' along the main-axis and the 'align-items' property to the center along the cross-axis.

image.png

2. Using Position

This is my personal go-to method if for some reason I cannot use Flexbox.

The 'position' property sets how the element is positioned in the document.

Here's how to center a div using 'position':

How does that work?

First we set the parent's position to 'relative' and the child's to 'absolute'.

We set the child's 'top' and 'left' property to 50% so it moves 50% towards the center.

Then we use the 'transform' property to move child from other side, truly centering it.

image.png

3. Using Tables

Earlier tables were the only real way to structure HTML, namely the syntax. But using CSS styling, we can make elements, such as 'div' tags behave like 'table' and 'td' tags.

image.png

4. Using Grid

Just like Flexbox, we'll use the 'justify-content' property to center the child horizontally and the 'align-items' property to center the child vertically.

image.png

5. Using Margin (only Flexbox)

Setting 'margin: auto' on a Flexbox item will set equal margins all both opposite sides, thus centering the item.

image.png

Wrap Up

Thanks for reading! I hope you liked this article on 5 different methods to center a div and I hope that they come handy to you in the future.

Do consider sharing this article with your friends – I'd really appreciate that. Stay tuned for more amazing content.