Vertical align anything with 3 lines of CSS

Posted 3 years ago     16677      css
127

With the useful help of transform element: we can vertically align whatever we want, even if we don’t know its height.

Just write:

.element {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  -o-transform: translateY(-50%);
  transform: translateY(-50%);
}

For those of you who have spotted, it is a similar technique to the absolute positioned one, but you don't have to set a height on the element or position-property on the parent.

Even works in IE9!

Comments


Nice, thanks for sharing!



No problem!



I love you



pretty damn genius



2 things:
1) the element have to be any kind of block display;
2) Complete version:
.element {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
}

Thanks



Note: does not work on IE<9

IE9 requires -ms-transform: translateY(-50%), IE10+ can use transform property.



Perfect snippet, will definitely use.



@wschalle CSS transform is reported to work on IE9, but does require the -ms vendor prefix.

This is supported in all other browsers, including mobile, a minimum of 6 versions back. This could/should definitely be usable for general common use at this point.



Updated the snippet to work in most browsers (tested IE9+)



@jonathan bird
Thank you! You have made one of the most painful tasks so simple.



Note:

I've noticed that this can cause text and icons to become blurry. I found this explanation on designer news:


What if the height of the container is some odd number pixels?

Let's say you have height: 145px and your translateY property will be like transform:translateY(72.5px) which means you're not pixel-perfect anymore. Your texts, icons, pictures will be all blurred.

Use it if pixel perfection doesn't matter.

PS: Table method is also 3 lines and it's cross browser already :)


display: table; /* parent*/ display: table-cell; /*child */ vertical-align: middle; /*child */"

(https://news.layervault.com/stories/12812-vertical-align-anything-with-just-3-lines-of-css)

This tip is pretty clever, none the less!



Great find Sean!



Sorry about that comment formatting! I can't edit it.



Wow! I would have never though to use that. Thats a great snippet!



You need to be logged in to post comments.



Welcome to Snippet Repo!

Discover, share and save useful code snippets.

Join our community over over 2,000 members! Currently a 48% acceptance rate. Apply for membership →