Vertical alignment - thinklab - thinklab

Vertical alignment

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:

.your-element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

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:

$('#element-to-be-centered').flexVerticalCenter();

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 Christian Redecen-Davies

Designer. Traveller. Photographer. Purveyor of fine pixels since 1999.

See all posts by Christian Redecen-Davies

Comments