The Simplest Way To Center Elements Vertically And Horizontally


The idea, of course, revolves around flexbox. First, we create a container in which we want everything to be centered:

You can place this container div anywhere you want. In the live example above we've made it take up the whole width and height of the page.

As we said earlier, we will be using only three lines of code. Here they are:

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

Every flex container has two axis for positioning elements. The main axis is declared with the flex-direction property (can be row or column, see docs). By omitting this rule, we've left the flex direction to its default row value.

Now all that we need to do is center both axis. It couldn't get any simpler:

Make the display type flex, so that we activate flexbox mode.
justify-content defines where flex items will align according to the main axis (horizontally in our case).
align-items does the same with the axis perpendicular to the main one (vertically in our case).

Now that we have set the rules for the vertical and the horizontal alignment to center, any element we add inside the container will be positioned perfectly in the middle. We don't need to know its dimensions beforehand, the browser will do all the hard work!