Vertical-Align : Middle Using Javascript : JQuery & Mootools

How do I vertically center my stuff inside this area ?

If you are looking for an answer for the above question then possibly you’ve landed on the correct page. The very first solution for this is to have vertical-align:middle in your css. But unfortunately this CSS property only works on table-cell and img.
Gavin Kistner have written a great article about this : How (Not) To Vertically Center Content.

Personally I feel it very cumbersome to style items as a table/table cell to get it aligned. I prefer using Javascript for positioning the block in middle. There may be situations where you would not like to use javascript then CSS is always there for you.

The basic idea in this approach is to wrap all child elements in a div and position this div in middle using Javascript.

Jquery Implementation

This is a jQuery plugin that will allow you to use the function in the jQuery chain. Something like :

$('#container').vAlign();

View Demo

Plugin Code

The Plugin code is as follows:

(function ($) {
$.fn.vAlign = function() {
	return this.each(function(i){
        $(this).children().wrapAll('
'); var div = $(this).children('div.nitinh-vAlign'); var ph = $(this).innerHeight(); var dh = div.height(); var mh = (ph - dh) / 2; div.css('top', mh); }); }; })(jQuery);

Mootools Plugin

This is a Mootools plugin that will allow you to use is on any Element to get its child elements align in middle. The code is something like this:

var v = new vAlign($('container'));

View Demo

Plugin Code

vAlign = new Class({

	initialize: function(element){
        this.element = $(element);
        
        var div = new Element('div', {
                    'class': 'nitinh-vAlign',
                    'styles': {
                        'position': 'relative'
                    }
                });
        
        div.set({ 'html': this.element.get('html') })
        this.element.set({'html':''})
        div.inject(this.element);
        
        var ph = this.element.getSize().y;
        var dh = div.getSize().y;
        var mh = (ph - dh) / 2;
        div.set('styles',{
            'top':mh
        });
    }
})

It’s not working for you

If this plugin is not working for you then may be there is some margin and padding applied in the code. Try changing it.

13 Responses

  1. Bård Øien #

    Nice to see vertical-align middle implemented in jQuery. I noticed it behaves slightly different from the “origial” vertical-align when I use Safari and resize the text, but I guess this should be quite easy to fix. :-)

    Reply
  2. Edd Turtle #

    Hey there, does this work with percentage heights and when a browser gets resized?

    Reply
  3. nitin #

    It will work with the percentage heights but will not work when browser gets resized.

    But it can be easily modified to get it working even on resize by attaching an Event on Resize..

    Reply
  4. lbo #

    I’ll be very grateful if you could give some line-by-line comment on your plugin.

    I could have it working by copy and paste, but not knowing why it work makes me uncomfortable. I know it’s a matter of basic js syntax, still I was not able to get it through once for all.

    now:

    // so, here you say “let’s start a function that will fire
    // when all the dom is ready”, correct?
    (function ($) {

    // now you’re saying “I’m defining a function called fn.vAlign”.
    // the arguments for this function would be… what?
    $.fn.vAlign = function() {

    // …an array of arguments (i), and the function will “walk” through
    // all those arguments. Or are you going to generate an array of functions?
    return this.each(function(i){

    // here, what does it mean (this)? the element i?
    // so the line below says “get all the children of the element wrapAll
    // that are inside element i?
    // And why there’s nothing inside the ” of wrapAll(”)?
    $(this).children().wrapAll(‘

    ‘);

    // ok, here you say “assign to var div the children called ‘div.nitinh-vAlign’
    // of the element (this)?
    var div = $(this).children(‘div.nitinh-vAlign’);

    // ok, that make me think that (this) can be one of the generic (i) elements
    // we are walking the fn.vAlign with, am I correct?
    var ph = $(this).innerHeight();

    // no problem with these two…
    var dh = div.height();
    var mh = (ph – dh) / 2;

    // and now you place the element corresponding to var div “halfway”
    // respect to (this). but here (this) can be one of the many (i) we’re
    // passing
    div.css(‘top’, mh);
    });
    };

    // why you end up with (jQuery)?
    })(jQuery);

    many thanks if you’ll have the time to answer to some of these very trivial question, it would be helpful to me in getting to understand how these js frameworks work.

    Reply
  5. Bradley Hilton #

    How would you go around making it resize again when the browser is changed? I’m not that much of a javascript person (jquery or mootools) and so I’m just very curious about how you could go about doing that. Thanks

    Reply
    • nitin #

      for getting this effect you’ll have to handle “on-resize” event. Just call this function onresize as well.

      Reply
  6. Larsson #

    I’m just about to try this, I have very little experience with javascript, if you could add the code for browser resize I’d be be hugely grateful.

    Can this be applied to vertically centering a website within the browser aswell? If not could you direct me to a script that can. Thanks

    Reply
  7. Nathan B #

    I found 3-4 other plugins first and tried them and they failed me, and I was about to give up, and then I found this and it worked! Huge thanks.

    Reply

Leave a Reply