CSS absolute centering

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.

Leave a Comment