Monday, August 2, 2010

Scaling Images using Max-Width and Expression (for IE)

Sometimes you'll find yourself needing to scale images on your sites. Most recently I was working on a CMS and I knew the customer would be uploading images, so I needed a good way to scale images and keep them to a max width. Fortunately, this is easy enough with a little CSS:

<html>
<head>
<style type="text/css">
#mydiv img
{
max-width:320px;
width:expression(this.width > 320 ? "320px" : this.width);
}

</style>
</head>

<body>
<div id="mydiv">
<img src="http://felixgilman.com/wordpress/wp-content/uploads/2008/04/kitten.jpg" />
</div>


</body>
</html>

In order to make this cross browser (FF & IE), we need to use max-width and an expression for the width. Try it out here: http://www.w3schools.com/css/tryit.asp?filename=trycss_dim_max-width

Enjoy.

No comments:

Post a Comment