Verticaly center an image inside a div
Some things you just can’t do with CSS or you can but it’s not easy at all, and one of them is verticaly center an image inside a div. Here is how you can do it easily with jQuery.
/*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);
The demo has some css is it, like horizontal centering (text-align:center) on the div, background, specific height and border so you can see the vertical centering is working perfect.
Easier then all that css tricks and hacks in order to make the same effect, isn’t it?
- Making image captions using jQuery
- Description text inside an input field
- Image splitting effect with CSS and JQuery
- Making Image Overlay Caption Using CSS
Did you absolutely LOVE this article... share it!