blog about graphic design, web design and marketing

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.

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
</div>
</div>

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.