简体   繁体   中英

How to center an overflowing image inside of a constraining div

I have a 240x240px div which contains a fading slideshow of images differing in sizes. I have each image set to a height: 240px with the width being automatic in proportion to its height. Some images are taller than they are wide (in proportion) so I center them inside the div using position: relative; margin: 0 auto position: relative; margin: 0 auto This works well except for images which overflow the 240px div . How could I go about centering images inside the div which overflow? I tried this (jQuery) but it doesn't work for some reason I'm sure I can't figure out:

if( $("div img").width() > 240 ) {
    $(this).css("margin-left", rv);
    var rv = -1 * ($(this).width() / 4) + "px";
}

The logic being, if the image expands the div in width, then shift it to the left by rv px, rv being 1/4 of the image's width (as 1/2 would clip the image in half on the left, so 1/2 of 1/2 effectually centering it?) My first guess would be that I can't reference $(this) as I am trying to, though I have no idea.

I know I could go and add individual inline CSS styles but that's messy and mundane. I'd rather have a script which can automatically calculate the center of the image then move it accordingly. Any ideas?

You can use CSS only:

LIVE DEMO

.imgHolder{
  border:1px solid #000;
  width:240px;
  height:240px;
  line-height:240px;  /* same as element height */
  font-size:0;        /* to perfectly vertical align middle the image */
  text-align:center;  /* to horizontally align middle the image */
}
.imgHolder > img{
  max-width:100%;
  max-height:100%;
  vertical-align:middle;
}

Iterate over the images and when they have loaded get the image width and the parent element width, compare the width, and if the image is wider than the parent get half of the difference and subtract that from the left margin to center the image horizontally.

$("div.centered img").each(function(_,el) {
    var img    = new Image(),
        parent = $(el).parent();

    img.onload = function() {
        var ma = this.width - $(parent).width();
        if ( ma > 0 ) {
            $(el).css('margin-left', ((ma/2) * -1));
        }
    }
    img.src = this.src;
    if (img.complete) img.onload();
});

FIDDLE

I'd recommend something like this:

div.center-img { background:url('/path/img.jpg') center center no-repeat; }

But your question would be answered with something like this:

$('div img').each(function() {
    if( this.width > 240 )
        $(this).css("margin-left", ((this.width - 240) / -2) + "px");
});

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