Vertical alignment - thinklab - thinklab

Vertical alignment

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+

Today we’re going to look at two ways that you can vertically align elements inside their parent container.

The CSS way

The first technique, by Sebastian Ekström, uses nothing but good old CSS. The key to this one is the CSS transform property, as seen below:

This method has decent browser support; it even works in Internet Explorer 9 (providing you include the appropriate vendor prefixes). If you’re using autoprefixer in your gulp task (as I do), then vendor prefixes are all taken care of!

The original source of this technique also includes an update that sets transform-style on the parent element, to prevent the element being vertically aligned from sitting on a half pixel and looking blurry. Nice!

The jQuery way

The second technique we’re going to look at, involves a neat little jQuery plugin from Paul Sprangers, called jQuery Flex Vertical Center. You simply include flexverticalcenter.js in your web page, along with a single line of jQuery in your scripts file, as seen below:

Now, you may ask why would we choose to include a js file, when we can achieve the same effect using pure CSS? Well, the benefit of using the jQuery version, is that Flex Vertical Center allows you to pass options into it. For example, you can define a parent selector and choose the CSS attribute that you want the alignment styles to be applied to. You can even apply an anonymous function that is called once the vertical centering is complete. Oh, and there is a vanilla JavaScript version of this plugin, too.

Happy coding!

 

Brought to you by Jay Pick

Jay is thinklab's front-end developer and WordPress guy. He enjoys reading about/learning JavaScript and has a soft spot for PostCSS fractional grid system, Lost Grid.

See all posts by Jay Pick

Comments