Aligning div center horizontally and vertically.

Hello,

As you can see that though the problem statement here is very simple, i.e to align div vertically inside another div, but the solution to the same is tricky.

Height is something that is very difficult to manage while laying out a template using css, especially when you have to vertically align the element to make it look sleeker. Suppose we have two divs: outerDiv class and innerDiv class like below:

<style> 
.outerDiv {
width:400px;
height:600px;
}
.innerDiv {
width:100px;
height:300px;
}
</style>
<div class=”outerDiv”>
<div class=”innerDiv”>
</div>
</div>

While I was browsing the internet for the solution I came up with following answers:

Method 1: Flex

This I can say is the simplest approach of all. But the shortcomings of this approach is the browser compatibility. Here we will be taking help of the display property flex. As we know flex is not compatible with all browsers, this solution will be limited to few browser versions. You can check its compatibility in caniuse.com. Let’s see the solution:

Here we just need to give display as flex to outerDiv class and align-items as center. It will do the job.

.outerDiv{ 
display: flex; /* establish flex container */
align-items: center;
}

Isn’t it easy!

Method 2: Position absolute and relative

This is a basic way to achieve the solution. It is based on the concept of position. Suppose if you give outerDiv class a position relative and innerDiv class a position absolute, then you can very well align the inner block with respect to the outer block as you have positioned the innerDiv at absolute position with respect to outerDiv. Now align it by giving the top property 50% to bring div down touching the center line and then take the div up by 50% of the innerDiv height using translate(-50%) to bring it in the center of the outerDiv.

.outerDiv{ 
position:relative;
}
.innerDiv{
position:absolute;
top:50%;
transform:translateY(-50%);
}

Method 3: Vertical Align

This uses the vertical-align property of the table. If you assign the outerDiv class the display as tabel-cell, then you can easily vertically align its content like below:

.outerDiv{ 
display:table-cell;
vertical-align:middle;
}

Method 4: Using the Unknown element before

As mentioned in CSS Tricks blog article ‘Centering in the Unknown’, A ghost element is used to centre the child container within it’s parent. As it will be given a height of 100%, there is no need to define heights for parent or child. It is an ideal method to use when the dimensions are unknown.

.outerDiv:before{ 
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.innerDiv{
display: inline-block;
vertical-align: middle;
}

So this is it, we have listed out all the best possible solutions to vertically align the div inside another. Try it out…

You can see the working demo in following link:

https://msmsmonika.github.io/VerticallyAlignDivDemo/

And get the code in my github.