Setting Maximum Width For Image In IE6, IE7 & Firefox

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, August 21, 2008

Follow me on Twitter as @mattiasgeniar

It seems simple, by using the “max-width” propery through CSS, however; IE6 doesn’t support it.

Here’s a simple “hack” to get it working, by using expressions (in javascript-like syntax) in CSS, that IE6 does support.

.my_img {
	max-width: 500px;
	/* Resize the image for IE6 */
	width: expression(this.width > 500 ? 500: true);
}

The code above is simple CSS, that will work for all major browsers to set a maximum width for an image (in this case: 500px).

All you need to do now is set the class on your image:

<img class="my_img" src="my-image.jpg" alt="" />

There are, of course, alternatives as well. You could call a javascript function that will determine the width of your image, and resize accordingly. Here’s the function.

function resizePhoto() {
	if (document.getElementById('photo_id')) {
		photo = document.getElementById('photo_id');

		if (photo.width > 500) {
			photo.width = 500;
		}
	}
}

And at the bottom of your page, you could activate it by:

<script type="text/javascript">
resizePhoto();
</script>

Again, this has a downside. Javascript can only resize your image, if it was loaded at the time you called the resizePhoto() function. You could solve this by preloading your images in javascript, or by using setTimeout() to call the same function a few seconds later (when you “guess” the image has loaded by then).

<script type="text/javascript">
resizePhoto();
setTimeout(resizePhoto, 3000);
setTimeout(resizePhoto, 6000);
setTimeout(resizePhoto, 9000);
</script>

This’ll try to resize the image right away, after 3 seconds, 6 and 9 seconds. If the image is already resized, these functions won’t do anything any more – so we can safely call them after each other.

The CSS style is probably the “cleanest”, and should be preferred. If for some reason you can’t use this, know that there are a ton of alternatives to be used – including javascript. You could also use the GDLibrary in PHP to analyse the image, and add the necessary “width='500′ " tags if the image exceeds certain sizes.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.