CSS – align div in center vertically

To place a div (or any block level element) of unknown size containing text, in center of its parent vertically, the following approach can be used.

  • First shift top of the div in container center using top:50%. For this element can be either relative or absolute.
  • Now shift div by negative 50% of its height using transform:translateY.

align-div-in-center-vertically

Example – div having one line text

<style type="text/css">
.outer {
  background-color:lightgray;
  width: 100px; height:100px;
}
.box1 {
   background-color:green;
  position: relative; top:50%;
  transform: translateY(-50%); 
}
</style>

<div class="outer">
  <div class="box1">Some text</div>
</div>
refresh

Example – div having multiline line text

Same approach will work for multiline text also.

<style type="text/css">
.outer {
  background-color:lightgray;
  width: 100px; height:100px;
}
.box1 {
   background-color:green;
  position: relative; top:50%;
  transform: translateY(-50%); 
}
</style>

<div class="outer">
  <div class="box1">Some text that will wrap to next line</div>
</div>
refresh

Related

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments