Centering element vertically and responsive

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

We want an element inside another element to be centered vertically.  We also want it to be responsive such that when the browser resizes  (and hence the containing element resizes), the inside element still remains centered vertically.

Let’s start out with this HTML with an “tagline” div positioned absolutely inside an “container” div …

starting-html

When positioned absolute with top=0 and left=0, the tagline will be pinned to the upperleft corner of the container looking like this …

starting-output

Which at this current time is not centered vertically yet.   If instead, we set top at 50% …

top-50-code

then it will look like this with the top edge of the tagline at the vertical center…

top-50

We need to shift tagline up by half its height.  We do this by using CSS transform in the y-direction (2nd parameter) …

css-transform-y

Now it looks vertically centered…

vertically-centered

And remain so even when the container size or tagline size changes….

still-centered-vertically

And if you want it centered both vertically and horizontally, do for both x and y …

centered-both

And you get both centered…

get-centered-both