Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 708
Xenon Thong Avatar asked Jul 09 '15 08:07

Xenon Thong


People also ask

How do I center absolute in CSS?

If you want to center something horizontally in CSS you can do it just by, using the text-align: center; (when working with inline elements) or margin: 0 auto; (when working with block element).

How do you center an absolute div?

With a relative positioned parent element, an absolute positioned element has a boundary. And with the left , right , top and bottom properties with a value of 0 (specifying the distance of the edges), and an auto margin, the absolute element is centered in the parent element.


1 Answers

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.

like image 65
Joel Almeida Avatar answered Oct 04 '22 06:10

Joel Almeida