Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

displaying image of unknown size inside div of fixed size

I have a <div> of fixed size say height:100px and width:100px. I have to display images of unknown size inside this <div> such that following cases arise:

  1. image width > div width
  2. image width < div width
  3. image width = div width
  4. image height > div height
  5. image height < div height
  6. image height = div height

no matter what, what is the best cross browser strategy, with support for legacy browsers, to display them with following criteria:

  1. no white space around image
  2. nicely centered (horizontally and vertically) if overflow
like image 929
timmaktu Avatar asked Jan 21 '14 17:01

timmaktu


1 Answers

To eliminate white space, set min-height and min-width to 100% for the images. To clip the overflow, set overflow: hidden on the div. To center overflowing images, use absolute positioning and some JavaScript to set top and left values based on the size of the image.

Edit: If the image is larger than the container in both dimensions, use some JavaScript to remove the minHeight and minWidth and then set the height to 100%. If that leaves whitespace on the width, set height to "" and set width to 100%:

.centeredImageContainer {
    height: 100px;
    width: 100px;
    overflow: hidden;
    position: relative;
}
.centeredImage {
    min-width: 100%;
    min-height: 100%;
    position: absolute;
}
function centerImage(img) {
    var container = img.parentNode;
    if (img.offsetHeight > container.clientHeight &&
        img.offsetWidth > container.clientWidth) {
        img.style.minHeight = "0";
        img.style.minWidth = "0";
        img.style.height = "100%";
        if (img.offsetWidth < container.clientWidth) {
            img.style.height = "";
            img.style.width = "100%";
        }
    }
    img.style.top = ((container.offsetHeight - img.offsetHeight) / 2) + "px";
    img.style.left = ((container.offsetWidth - img.offsetWidth) / 2) + "px";
}

jsfiddle.net/QRU4w/2

like image 159
gilly3 Avatar answered Sep 18 '22 13:09

gilly3