CSS3: How to vertically center align HTML elements for variable heights

Let me put it this way, it is just a nightmare for front-end developers who have faced the situation for the first time without knowing a proper way to do it. For fixed height elements, vertically center aligning is really easy with some calculation and adding some padding in the parent element or some margin in the child element. But when the heights of those elements are not fixed (a regular case in responsive front-ends), that margin-padding method does no good rather than complicating the situation even more. You can use JavaScript, but who wants to use unnecessary scripting, especially if you are like me who cannot tolerate unnecessary scripting and is a fan of elegance and performance. display: table-cell; ? No, it will not work as you expect in cases where absolute positioning is involved.

Actually, there is a very easy way to vertically center align elements and once you see how easy it is, you’ll never use anything else for this task. CSS3 transform property will do the job for us. Here is a pen I made for you to demonstrate the vertical center aligning with CSS3 transform.

Basically, what we’ll do here is to apply position:relative; and top:50%; in the child element (with class name .child in the demonstration), so that it starts from half-way down along the variable height of the parent element (with class name .parent in the demonstration). And then, we’ll push it up half the size of its own height using transform:translateY(-50%); with all browser specific prefixes, so that the vertical centers of both parent and child are in the same position.

One thing I need to mention here is that it will not work for IE 8 or earlier. But then again, it is 2015, right? 🙂 Hope this trick help you in some projects.

Advertisements

Ask a question or leave a reply!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s