Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

centering image vertically in fluid container

centering image vertically in fluid container

Problem

//Fluid Width And Height Some content..............
//Fluid Width and Height

CSS:

#A {
width:50%;
min-height:50px;
}
#B{
min-height:50px;
}
#B > img {
width:55%;
}

What I want is:

  1. Div B should always have the same height as Div A.
  2. Image inside Div B should be centered vertically in Div B.
  3. Way to trigger this code after the Divs A and B have commpletely loaded and their repective css has been applied.

Fiddle of markup: http://jsfiddle.net/LjyzM/

Problem courtesy of: user2556089

Solution

Set the height of B to the same height as A, then set the top margin of the image to the container height minus the image height divided by two :

var h   = $('#A').height(),
    img = $('#B').height(h).find('img');

img.css('margin-top', (h-img.height())/2);

FIDDLE

EDIT:

to make sure the image is loaded, you can use this trick:

$('img', '#B').one('load', function() {
    var h = $('#A').height();

    $('#B').height(h);
    $(this).css('margin-top', ( h - $(this).height() ) / 2);
}).each(function() {
    if(this.complete) $(this).load();
});

EDIT AGAIN:

if you have to wait for more content to load, do:

$(window).on('load', function() {
    var h   = $('#A').height(),
        img = $('#B').height(h).find('img');

    img.css('margin-top', (h-img.height())/2);
});
Solution courtesy of: adeneo

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

centering image vertically in fluid container

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×