jQuery Center image vertically within it's container

Cross-browser method to vertically center an image within it's container. IE doesn't always fire the load event for images if they are cached, so we iterate through them first, then handle the load event.
(function() {
	var containerHeight = 128;
	function verticalCenterImage() {
		var height = $(this).height();
		if (height < containerHeight) {
			$(this).css('margin-top', (containerHeight - height) / 2);
		}
		else {
			$(this).css('margin-top', 0);			
		}
	}
	$('#container img').each(verticalCenterImage).load(verticalCenterImage);
})();
Posted by
Snippet Viewed 1655 times.

Share your jQuery code snippets:

  • Get some recognition & a link back to your site.
  • Create your own code library.
  • Help your fellow developers, as they have helped you.

 

Submit | Browse

Most Recent jquery snippets

Most Viewed