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.
jQuery
$(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);
});
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.
Final words
Easier then all that css tricks and hacks in order to make the same effect, isn’t it?
Related posts:
- 10 Awesome jQuery and JavaScript Snippets
- Making image captions using jQuery
- Description text inside an input field
- Image splitting effect with CSS and JQuery
- How to make a completely reusable jquery modal window
Slobodan Kustrimovic
This author has yet to fill his BIO.
Did you absolutely LOVE this article... share it!
Comments
Hi,
I have a problem with multiple photos (in different sizes) in a page. Vertical align seems to be not correct. Please help.
Leave your own!