CSS absolute centering

Recently i've came across this method used to position an element both horizontally and vertically to the center. However, I wasn't able to figure out what each of the property is doing. Would someone be able to explain to me what is the effect upon setting top:0, bottom:0, left:0, right:0?

(Would be great if you're able to explain it using layman's term or provide an illustrative image.)

Also, what is the use of setting the display to table?

.absolute-center {
  position: absolute;
  display: table;
  height: auto;
  width: 500px;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  border: solid 1px red;
}
<p class="absolute-center">What is this sorcery?</p>

You can reduce the css to this:

.absolute-center {
    position:absolute;
    width: 500px;
    height: 100px;
    margin: auto;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    border: solid 1px red;
}
<p class="absolute-center">What is this sorcery?</p>

The absolute element with properties like bottom: 0; top: 0; left: 0; right: 0; will fill all the space.

So, whats the secret/sorcery here?

You are defining the width and height of the element. So, even if he wants to fill all the space he will be limited by your width and height.

The secret is the margin: auto, why? Because the element will fill the remain spacing with margin. That way because you have width and height defined it will have that size but the margin will fill the rest of the container/parent in the way auto works, equal sized both sides.

Because of the margin:auto you need width and height defined.


Let's break it a bit:

If you have the following CSS (I apply it to your current markup):

.absolute-center {
    position:absolute;
    height: auto;
    margin: auto;
    background: red;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
}

You can see that the div.absolute-center fills the entire parent element (in this case body), just by setting all properties top, bottom, right and left.

Demo: http://jsfiddle.net/0osLv27k/

So when we add width (additionally height) to the previous CSS, the element is limited to this size.

Demo: http://jsfiddle.net/0osLv27k/1/

And finally the magical margin: auto which makes the element to be centered.

Demo: http://jsfiddle.net/0osLv27k/2/