Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I vertically center align a position:relative element?

How do I vertically center align the parent container to the canvas which has position:relative? The parent container has a child element with position:absolute. The child element has been positioned in the center of the parent container.

Here's a snippet:

.container {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: red;
  margin: auto;
}

.item {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: blue;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}
<div class="container">
  <div class="item"></div>
</div>
like image 508
Vennsoh Avatar asked Aug 28 '12 11:08

Vennsoh


People also ask

How do you vertically center a relative div?

Set the position for the parent to "relative", and for the child, set it to "absolute". Set the top, bottom, left, and right properties for the child. Set the margin to "auto" to make all margins equal and make the child <div> to be centered vertically as well as horizontally.

How do you center an element with a relative position?

Method 1. First Method: We use 'left:0' , 'right:0' , and 'margin:auto' to achieve horizontal centering. Then, in order to achieve vertical centering, we use 'top: 50%' , which makes the element stay almost centered - this will only center the element according to its top boundary.

How do you center an element vertically?

you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%.

How do you center vertically with an absolute position?

Absolute Position A common technique for both horizontal and vertical centering is using an absolute positioned element as child of a relative parent. What we do is basically position our child element left by 50% and we shift it back by half of its size using a negative 50% translateX in order to get it centered.


1 Answers

One solution is to wrap your .container with two wrappers; give the first one display: table; and height: 100%; width: 100%; and the second display: table-cell; and vertical-align: middle;. Also make sure your body and html have full height.

Here's a little working demo: little link.

Another method is to apply top: 50%; to your .container and margin-top: -150px; (300px / 2 = 150px). (Note that this method requires you to know the exact height of your container, so it might not be exactly what you want, but it might as well be!). A little working demo of this latter method: another little link.

I hope that helped!

like image 87
Chris Avatar answered Sep 18 '22 22:09

Chris