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>
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.
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.
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%.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With