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" />');
$(el).children('.vert').css({
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
</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.
If you have any questions, let me know.
Tags: jquery, css, styling, alignment, html, javascript, utilities
Some other articles you might enjoy...
| Snazzy jQuery Form Alert Boxes | Tuesday, February 9, 2010 |
| JQuery/PHP: Simple Random Text Generation Box | Monday, June 22, 2009 |
| Fixing the 100% width text input field | Friday, July 1, 2011 |
| jQuery is-or-is-child-of function | Saturday, June 25, 2011 |
| E-mail Newsletter Form with jQuery, AJAX, MySQL and PHP | Sunday, March 14, 2010 |
design 16 articles
user interface 7 articles
php 7 articles
code 7 articles
web 6 articles
jquery 6 articles
tutorial 6 articles
picture 5 articles
marketing 5 articles
html 4 articles
2012
2011
2010
2009