Proportionally resize images with CSS (and maybe JS)

With CSS only:


img { height: auto; max-width: 99%; }

I normally used only max-width: 99%;, but I found it tends to produce images which are too vertically stretched in some cases, and I am of the opinion that images should always preserve their aspect ratio, unless you're trying to create some strange effect.

Tested in Firefox 3.5, Chrome 3, and Safari 3 -- let me know if it works (or not) in other browsers!

If it doesn't work, I have been playing with some javascript that you could use. In theory, something like the following could be used instead, although I can't think of an scenario where CSS support was bad enough that JS had to be used... oh wait, I just remembered this script. Ha!

Anyway, here's the javascript code:


if(document.getElementsByTagName)
{
    var imgs = document.getElementsByTagName("img");
    var i, el, nw, w, h, nh, cw, container;
    for(i = 0; i < imgs.length; i++)
    {
        el = imgs[i];
        nw = el.naturalWidth;
        w = el.width;

        container = el.parentNode;
        if(container == null) { continue; }

        cw = container.clientWidth;

        if(nw > cw)
        {
            nh = el.naturalHeight;

            el.width = Math.round(0.99 * cw);
            el.height = Math.round(el.width * 1.0 * nh / nw);
        }

    }
}

I'm not sure if I'm being extra cautious with the if(document.getElementsByTagName) check.

Of course, if you want to do things properly, this script should only be executed once the page and images have been fully loaded, because only at that point the real size of the images (also known as the naturalWidth and naturalHeight properties) can be accessed.

Corrections and suggestions are gladly welcome.