Centering Div using Flexbox

There are generally two ways to center a div, margin and flexbox. Centering Content using flexbox is much more easier to implement.

Center a div Horizontally

Suppose there are two divs: container and child.

1
2
3
<div class="container">
<div class="child"></div>
</div>

Traditionally, you can center a child div horizontally using margin

1
2
3
.child {
margin: 0 auto;
}

You will offen see it used in the wrapper div that contains all the rest of the HTML document.

1
2
3
4
.wrapper {
max-width: 1440px;
margin: 0 auto;
}

To center a child div horizontally using Flexbox, you need to apply display: flex and justify-content:center to the container div

1
2
3
4
.container {
display: flex;
justify-content: center;
}

Center a Div Vertically

To center a div vertically, you only need to apply align-items: center the container div

1
2
3
4
.container {
display: flex;
align-items: center;
}

Center a div Vertically and Horizontally

To center a div both vertically and horizontally, apply both justify-content:center and align-items: center the container div

1
2
3
4
5
.container {
display: flex;
justify-content: center;
align-items: center;
}

Reference