Vertically center with css

Vertically Center anything with just 3 lines of CSS

For a web developer always face some critical issue those can be solve two or three lines of codes. Today i am going to show a technique how to Vertically Center a div or an image.
With just 3 lines of CSS (excluding vendor prefixes) we can with the help of transform: translateY vertically center whatever we want, even if we don’t know its height.

The CSS property transform is usually used for rotating and scaling elements, but with its translateY function we can now vertically align elements. Usually this must be done with absolute positioning or setting line-heights, but these require you to either know the height of the element or only works on single-line text etc.

So, to vertically align anything we write:

.element {
position: relative;
top: 50%;
transform: perspective(1px) translateY(-50%);
}

That’s all you need. It is a similar technique to the absolute-position method, but with the upside that we don’t have to set any height on the element or position-property on the parent. It works straight out of the box, even in Internet Explorer 9. To ensure browser compatibility, remember to add the proper vendor prefixes. At the time of writing, you need -ms-transform and -webkit-transform to make sure it works everywhere.

You can find a demo of it here:

Leave a Comment

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

Scroll to Top
0 Shares
Tweet
Share
Pin
Share