简体   繁体   中英

centering image vertically in fluid container

<div id="A"> //Fluid Width And Height
Some content..............
</div>

<div id="B">
   <img src='xyz.jpg'>//Fluid Width and Height
</div>

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/

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);
});

http://css-tricks.com/centering-in-the-unknown/

<div class="something-semantic">
   <div class="something-else-semantic">
       Unknown stuff to be centered.
   </div>
</div>

.something-semantic {
   display: table;
   width: 100%;
}
.something-else-semantic {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM