Saw an interesting post on reddit yesterday, it was in r/askreddit. The question was along the lines of “What question do you ask someone in your industry to immediately tell if they are faking it?” One of the higher voted comments was “How do you vertically align an element?” The answer was using transformY. I’ve seen a lot of methods that were ridiculous but it appears this is the common way to do it now. Using position you can set an element to 50% of it’s parents height but the axis is based on the top of the element. By adding a -50% transformY it will bump the element up so the middle is aligned to the middle of the parent. It’s beautiful!
Can you tell?
<div class='tyex-container'>
<div class='tyex-valign'>
This box is vertically aligned.
Can you tell?
</div>
</div>
<style type='text/css'>
.tyex-container {
height:300px;
position:relative;
border:#ccc solid 1px;
}
.tyex-valign {
position:relative;
top:50%;
-webkit-transform:translateY(-50%); /* added prefixes, thanks @isotrope */
-ms-transform:translateY(-50%);
transform:translateY(-50%);
background:#ccc;
}
</style>