I just discovered a cool CSS trick. We’ve recently started using a wiki for collaboration. People are able to attach images in the document, but the images show up as whatever size the image they upload is. So if they upload an image that is 2000 pixels wide, it fills the browser window.
CSS to the rescue. CSS 2.0 supports the max-width attribute. This is great but doesn’t work in Internet Explorer. In my browsing I came across this little IE specific trick. You can actually embed javascript in a CSS file. So this little block in my CSS file limits the size of images for both Firefox (and Opera) and IE (don’t know about Safari).
div.wiki img {
/* for CSS 2.0 compliant browsers */
max-width: 500px;
/* for IE only */
width: expression(this.width > 500 ? 500 : true);
}
5 Comments
This is great…I’ve definitely been wondering how I could do this in the past.
Incidently, this does not seem to work correctly (at least in some cases) in Konqueror or Safari. The images get squished and the aspect ratio thrown out of whack.
Here is a solution that seems to work in Konqueror. I’m still not sure about Safari. It’s too bad I had to resort to javascript, but whatever works…
window.onload = resizeImages;
function resizeImages()
{
var imgs = document.getElementsByTagName(‘img’);
for( var i=0; i imgs.length; i++ ){
if( imgs[i].width > 500 ){
var factor = imgs[i].height / imgs[i].width;
imgs[i].width = 500;
imgs[i].height = 500 * factor;
}
}
}
The comparison in the for loop should be a less than. Typepad won’t let me put one there.
Cool tip; the failure of max width in IE has botched more than one design for me in the past.
I didn’t know you could embed JavaScript directly into CSS like that… nice!
Omg! This is the coolest ever. I’m a Firefox girl but have to use IE and, boy, is it s-o m-u-c-h t-r-o-u-b-l-e. You saved my layout! Thank you!