Vanilla CSS: all the methods that we can use to center a div

Journey to the Hello World
2 min readSep 4, 2021

--

In this post, I will simply list all the methods that I can come up with when a div element is required to be placed in the center vertically, horizontally or both.

Center a div inside a div

This is the simple one. If the inner-div has fixed width and height properties, the common method is to set the inner-div’s margin property to auto.

Center a div inside a div

Center any element vertically inside a div

We can use CSS transform to center any element inside a div.

Center a div at the bottom of the page

The target div must have width property and wrapped by another div. The wrapper div element have position set to absolute and we can adjust the gap between wrapper div and the bottom of the page by setting bottom property. If you want to center the outer-div at the top of the page, you can set the top property of the outer-div instead.

Now the question become how to center a div inside a div. We just need to set target div margin properties to 0 auto.

Center a div both horizontally and vertically in the page

The target div should have:

  1. position set to absolute .
  2. top, bottom, left , right set to 0.
  3. Non-zero width and height

Center a div in a page Responsively

This is often done by setting the margin and max-width properties.

Center a div inside a div Responsively

A common method is to set the max-width property of inner-div.

Center two divs side by side and Responsively

The common method is to set the inner div to inline-block, and then set the container’s text-align property.

Center the div horizontally and vertically in the page with Flexbox

We declare the container display as flex. The height property of the container needs to be greater than the item. By setting the container’s height: 100vh, we make the height of the container the height of the entire browser window. To center the target div in the page, we set the container’s align-items and justify-content to center.

Center a dynamic div horizontally and vertically

Center the div horizontally and vertically by setting the display attribute value to table. The height and width of center-div are set responsively.

That’s all I’ve come up with so far, if you have anything to add, you can leave a comment. :D

--

--