blog about graphic design, web design and marketing

The D. Drew Design Blog
oct 10

jQuery Vertical Align Function

You can't vertically align content very easily for websites unless they're contained in a <table>, but using tables isn't always an option. Since this is a problem I frequently encounter, I decided to write a jQuery function that does it for you. And since I'm all benevolent and stuff, I've decided to provide it here for your enjoyment.

It's not a true jQuery plugin, because I didn't write it as an extension, but it's easy enough in implementation.

function vertAlign(el, offset){
    $(el).wrapInner('<div class="vert" />');

        overflow: 'hidden'

    var box_height     = $(el).children('.vert').height();
    var container_height = $(el).height();
    var center_pad     = (container_height - box_height)/2;

    $(el).children('.vert').css('padding', (center_pad + offset) + 'px 0 ' + (center_pad - offset) + 'px');

To use this function, just copy the code above, and paste it after your $(document).ready(function(){});. To apply it to the DOM, suppose you have the following HTML structure:

<div class="one">
    <div class="two">
        Two's Content

If you wanted to center the content of .two, you would use the following code inside your .ready() statement:

vertAlign($('.two'), 0);

You'll notice a 0 after the call to the element in question. This is a vertical offset. It's an integer, and it's applied in pixels. A positive value here will result in your inner content shifting downward; a negative value will result in it shifting upward.

What the function does is wrap your content in a new <div> with the class vert, and then position that <div> using padding. Obviously, in order to work, the containing <div> (.two in the example above) will need to have a height, so make sure it has a defined height, is floated, or has overflow: hidden or overflow: auto applied to it.

If you have any questions, let me know.

Tags: jquery, css, styling, alignment, html, javascript, utilities

Some other articles you might enjoy...