I have a <div>
of fixed size say height:100p
x and width:100px
.
I have to display images of unknown size inside this <div>
such that following cases arise:
no matter what, what is the best cross browser strategy, with support for legacy browsers, to display them with following criteria:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With