We did it wrong for a very long time. Actually it’s not that we did it wrong, we just used to put way too much energy in centering a content and keeping it centered on any screen size, when a simple easy command could do the job.
Horizontally align a content or div is easy, just use
text-align: center; or
margin: 0 auto; and you’re done. When you try to vertical align though, the latter code does not translate (for some reason, the value of a ‘margin-top’ or ‘margin-bottom’ set to ‘auto’ is 0), and you usually need to get your hands (and code) dirty. We used to display the div that needs to be centered at
top:50%; and then evaluate its height to adjust the position according to its size. However, this can be tricky as you may have very little control on the height of your div (just picture a text that can have any length!). And of course, this method requires to begin all over again when adapting the design to smaller screen sizes.
We recently discovered that we could use
transform: translateY(-50%); in CSS3 to vertical align, and that the whole “centering” issue could be addressed with a simple
transform: translate(-50%,-50%);, so we thought we’d share the trick!
Here’s an example. Imagine you want to center the following text, your php file looks like this:
And the CSS:
You can click for demo here: http://jsfiddle.net/nm09rbqv/4/