Vertically aligning elements

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

[css].parent{
display: table;
width: 100%;
}
.child{
display: table-cell;
text-align: center;
vertical-align: middle;
}
[/css]

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:

[css]
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}[/css]

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).

transformy

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.

top50


Comments

Leave a Reply

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