Vertically aligning elements

For a long time I’ve always been using the following method of vertically aligning elements on a web page:

display: table;
width: 100%;
display: table-cell;
text-align: center;
vertical-align: middle;

This method works good across all browsers and includes solid IE support down to IE7. The downfall of this particular method is that it requires two html elements in order for it to work (a parent and a child).

Using CSS3 transforms property, we can now vertically align elements with just 3 lines of css:

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

Transforming the element on the Y axis with a negative 50% of the height the element is currently contained in will pull it up half way (more than likely outside the parents width and height).


Now if we add a top: 50% it will pull the element back down directly in the center of whatever parent container the element is sitting inside of.


Leave a comment

Your email address will not be published. Required fields are marked *