Originally I followed this article which used position: relative
on the child element: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/
http://codepen.io/anon/pen/KpWKWg
But I couldn't get it to work on my code for the life of me:
Then I found these instructions which use position: absolute
on the child element: https://css-tricks.com/centering-css-complete-guide/#vertical-block-unknown
http://codepen.io/chriscoyier/pen/lpema
And when I tried it on my code it finally worked:
Any good explanations?
By default, all elements on DOM are
position:static
. Properties liketop, left, right, bottom
aren't usable with a statically positioned element. Using any other positioning context likerelative
absolute
orfixed
allow you to use these values.The method used in the solution is to push an element from top by
50%
and then pulling it upwards by half theheight
of the element. This is wheretransform
comes into play.Now, you can see that both of your articles use a different positioning context other than
static
. In first, it uses 'relative' and in the css-tricks example you seeabsolute
.The reason why your code isn't working because
transform
works on block-level elements but your text is inside aspan
. Add adisplay:block
to it and you should be good to go.I also noticed that you have
transform: translate(-50%,-50%);
which should just betranslateY(-50%)
to compensate for the height of any box you are trying to vertically center by pushing it fromtop
by50%
.You miss
display: block;
on.valign
. The transform element as it seems should be applied to a block element, not inline. Here is the documentation:Also if you need to center only verticaly (and not horizontaly), change you
transform
s to: