Vertical alignment of div

Posted By : Shivam Gupta | 01-Jun-2016

In this blog I want to discuss that how to align any div vertically centered, then there are different ways of doing this, which is given below -

1) Equal top -bottom padding: In this way at first we get outer div height, then inner div height. After then the top-bottom padding would be (outer-div-height - inner-div-              height/2).

HTML: - 

<div id="outer">
<div id="inner"></div>
</div>

CSS: - 

#outer{
width: 200px;
height: 200px;
}
#inner{
width: 50px;
height: 50px;
padding: 75px 0px 75px 0px;
}
 
2.) Using css3 transform method: In this method, at first we assign relative or absolute position to inner div, then keep 50% away from top, then we transform that inner div (-50%), so that div may be positioned vertically centered.
 
HTML:
 
<div id="outer">
<div id="inner"></div>
</div>
 
CSS:
#inner{
width: 50px;
height: 50px;
position: relative;
top: 50%;
transform: translateY(-50%);
}
 
3) Using flexbox: In this way, we make div flex by assigning the css property, then we position that inner div vertically centered.
 
HTML: 
 
<div id="outer">
<div id="inner"></div>
</div>
 
CSS: 
#outer{
  height: 300px;
  width: 200px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  resize: vertical;
  overflow: auto;
}

#inner {
 width: 30px;
 height: 30px;
  background: black;
  color: white;
  resize: vertical;
  overflow: auto;
}
 
4) Table method:  In this method, at first we assign css property to outer div. so that it may work as a table, then assume inner div as a table-cell by assigning specific css property.
 
HTML: 
 
<div id="outer">
<div id="inner"></div>
</div>
 
CSS: 
#outer {display: table;}
#inner {
    display: table-cell;
    vertical-align: middle;
}
 

THANKS

About Author

Author Image
Shivam Gupta

Shivam is a versatile UI developer with html, css, scss, js, angularjs technologies. He likes chess, cricket and reading book.

Request for Proposal

Name is required

Comment is required

Sending message..