Explanation needed for a trick to center div on the page

You have a div


The following CSS code will center the div on the page (both horizontally and vertically):

div {
    width: 100px;
    height: 100px;
    background-color: blue;

    position: absolute;
    margin: auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;    

I don’t understand how it works. Can someone explain to me? Thank you.

position: absolute takes the element out of the normal flow, since there isn’t any relative parent, it goes to the top left of the page.

top, bottom, left and right makes the element takes the whole space, in this case, it will occupy the whole page.

width, height by giving the element a width and height, it will respect that instead of filling the whole page. And it will force the browser to calculate the value of margin: auto.

margin: auto this is where the trick lies, normally, margin: auto works only for centering the element horizontally. But because we make the element absolute, the browser will give equal value to margin-top and margin-bottom.

It’s quite complex why this happens, and I also don’t understand it fully, but it looks like it have something to do with margin collapsing.

I also found this full-article: https://www.smashingmagazine.com/2013/08/absolute-horizontal-vertical-centering-css/


Thanks for your answer @ghukahr