pepebe
9/22/2012 - 1:12 PM

JS: Verticaly center an image inside a div

JS: Verticaly center an image inside a div

Source: http://web.enavu.com/daily-tip/verticaly-center-an-image-inside-a-div/

$(window).load(function(){  
    /*we are using $(window).load() here because we want the coding to take 
    effect when the image finishes loading. */  
  
    //get the width of the parent  
    var parent_height = $('#the_image').parent().height();  
  
    //get the width of the image  
    var image_height = $('#the_image').height();  
  
    //calculate how far from top the image should be  
    var top_margin = (parent_height - image_height)/2;  
  
    //and change the margin-top css attribute of the image  
    $('#the_image').css( 'margin-top' , top_margin);  
});