displaying image of unknown size inside div of fixed size
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
edit:
fiddle
html:
<div id="myPic"></div>
css, if you want a big pic to shrink to fit while still filling the whole div, and want a small pic to expand to fill the whole div:
#myPic{
width: 100px;
height: 100px;
background-image: url(/abs/path/img.jpg);
background-size: cover;
}
css, if you want a big pic to only display a window of the middle without resizing:
#myPic{
width: 100px;
height: 100px;
background-image: url(/abs/path/img.jpg);
background-position: center center;
}
I don't know of a way to both expand small images to fit, while not shrinking big images.