08 Apr 2009 @ 8:53 PM

Evening All.

Everyone loved valign=”middle” on tables… well life just got better with jQuery. This plugin works flawlessly however make sure that both the element itself and the parent element do not have any top/bottom paddings, else please modify it using the .outerHeight() property that takes into consideration the padding/border of those elements. Tweak and use as necessary.

the JQuery

(function ($) {
// VERTICALLY ALIGN FUNCTION
$.fn.vAlign = function() {
    return this.each(function(i){
    var ah = $(this).height();
    var ph = $(this).parent().height();
    var mh = (ph - ah) / 2;
    $(this).css('paddingTop', mh);
    });
};
})(jQuery);

You can get the benefits of valign=middle no problem.

So just put the jQuery framework script then this script above and call the elements you want to be valigned=middle by using this

$("#box").vAlign()

Also another VERY NIFTY thing to do is, in order to prevent the user from seeing the javascript process (since first HTML is loaded, then CSS file is loaded, then any images are loaded, then JS is processed) you can do this.

First you need an .outerBox that encompasses the Box element, and then you need to have the box element with a declared height, like #box { height: 300px;}. This workaround is only good for IE 6 since that sucks donkey balls, and has a JS rendering engine from 1000AD. however depending on the amount of content being displayed (like entire columns) IE7 which appeared in 2000AD may require this fix also. Other browsers are OK so this is BS

CSS:

#outerBox { display: none;}
#box { height: xxxpx;}

Javascript:

function alignThis(){
$("#box").vAlign();
$("outerBox").css("display","block");

End of story.

And for the other more compatible browsers you can put this in another JS file. The previous one was inserted in the HTML using conditional comments <!--[if IE lte 7]> <script src="./../js/biteMe.js" type="text/javascript"/><![endif]-->

$("#box").vAlign(); and just use Conditional comments to put the IE specific things in so they wont see them, and since you are linking 2 different JS files, (again with conditional comments) you script WONT JAM.

Complex solution for an ancient problem.

Cheers

Posted By: Dinulescu Alexandru Adrian

Last Edit: 07 Jan 2010 @ 07:33 PM

EmailPermalink

Responses to this post » (None)

You must be logged in to post a comment.