What's the right way to auto-scale images such that they fit exactly inside the browser window, while preserving their aspect ratio?
The images in the DNA Lounge photo and flyer galleries auto-scale to fit in the window. However, this only works horizontally. If the image is wider than the window, it shrinks, but if the image is still taller than the window, it does not. I'd like to make it scale in both directions, so that on an iPhone, both portrait and landscape images default to being fully visible, regardless of the phone's orientation.
The current (horizontal-only) behavior is is accomplished in CSS. The image has:
- width:100%; height: auto;
max-width:900px; max-height:600px;
I think that there's no way to make the image fit within the window using only CSS (and also preserve the image's aspect ratio). I think the only way to accomplish that is with Javascript.
So I tried this:
function scale_images() {
var maxw = window.innerWidth;
var maxh = window.innerHeight;
var aa = document.images;
for (var i = 0; i < aa.length; i++) {
var img = aa[i];
var w = img.naturalWidth;
var h = img.naturalHeight;
var r = h/w;
if (h > maxh) {
h = maxh;
w = h/r;
}
if (w > maxw) {
w = maxw;
h = w*r;
}
img.style.width = w + "px";
img.style.height = h + "px";
}
}
document.body.onload = scale_images;
document.body.onresize = scale_images;
document.body.onorientationchange = scale_images;
Well, that sort-of works, except that the viewport sizes I'm getting on iPhone are weird. In portrait mode, I am getting a 320x356 viewport (as expected) but when I rotate to landscape, I'm getting 320x139 instead of 480x208, which means the document is scaled up and the font size increases. What's the fix for this, short of disabling all scaling (even pinch-zooming)?
Surely others have solved this problem? Got examples?