How to center vertically and horizontally using CSS3 transform



In this article I will show you how to center vertically and horizontally using CSS3 transform property. Centering horizontally is easy, but vertical alignment has always been a bit tricky with CSS.

I created a class for this that I called centerme which you can freely use in any project. You can also remove the horizontal alignment from it and keep only the vertical alignment.

A demo of this trick, together with the source can be found below.

Some more explanation

The actual class that centers an element vertically and horizontally is this:

.centerme {
    margin: 0 auto;
    display: table;
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

I have applied this centering class to the container that has the image and the text. I have also added the centering class to the text itself.

Horizontal centering can be done simply by setting margin : 0 auto; and display: table;



Vertical centering, however is a bit more tricky. Luckily CSS3 comes to the rescue with the transform property (again)!

First, we lower the element vertically by 50% from the top of its parent container like this:

position: relative;
top: 50%;

Now the element will be positioned a bit too low. This is because we need to move the element up by 50% of its own height. We do this by using transform.

-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-o-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);

 That’s it!

I hope you have enjoyed this quick little trick. Don’t forget to like and follow this blog on your favorite social media!

Share the knowledge!
Facebook3Twitter111Google+5StumbleUpon74Reddit1LinkedIn4tumblrbufferDigg

Comments

You may also like...

x
Stay updated