I am attempting to have a cross browser solution for vertical alignment of an element (it has been documented so many times that I’m not sure where to attribute it). It works great except for when using Chrome where the element contains an image. This is because Chrome determines the height of the image is 0 because it hasn’t loaded it yet I believe. How do I modify the below jQuery to fix this?
Thanks!
$(document).ready(function() {
$(".valign").vAlign();
});
(function ($) {
$.fn.vAlign = function() {
return this.each(function(i){
var ah = $(this).height();
var ph = $(this).parent().height();
var mh = Math.ceil((ph - ah) / 2);
if (mh < 0) {
mh=0;
}
$(this).css('margin-top', mh);
});
};
})(jQuery);
Just replace your
$(document).ready()with$(window).load(). It won’t execute until all the referenced images load.