Sunday, September 6, 2015

Vertical align middle with css

Lets take a look at various methods of aligning an element in the middle of its parent vertically.

1.Table method


     Vertical-align property doesn't works on display block elements.So, one way to get the vertical-align property work is to set the parent element display:table and its child element (which is to be aligned) display:table-cell.Then the vertical-align property will work and the element will be aligned in the middle.

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




2.Line-Height method

   Another method of aligning an element vertically is set line-height property to the container div.
We can align a text vertically by specifying the line-height to the container.Usually to middle the text exactly in the middle , the line-height provided is equal to the total height of the element.

.parent{
  height:30px;
  line-height:30px;
}



3.CSS3 - Transform method


     With css3 transform method an element can be aligned vertically middle using just three line of code.

.element{
    position:relative;
    top:50%;
    transform:translate(-50%);
}

No comments:

Post a Comment