Resources: Max-Width and Max-Height in Internet Explorer

Inconsistent implementation of css standards across different browsers has long been a thorn in the side of many web designers. Internet Explorer's inability to properly and consistently apply the css properties of "max-width" and "max-height" has been a particular bother to me since many of the sites I create contain user created photos of varying sizes and aspect ratios.

While versions of Internet Explorer below 8 don't properly render these values, there are some special scripted IE only values that do the same thing called "expressions". Support for expessions is ending with IE8, you can read about it here, but it's still a good trick to know and use since a great many folks out there still use older versions of IE for a variety of reasons.

If your image was contained in a div with an id of "test" and you wanted to make the maximum width of the image be 200px this is how you would write it:

#test img {
max-width:200px;
width: expression(this.width > 200 ? 200: true);
}

The first line contains the max-width value for css compliant browsers, the 2nd line contains the expressions for older versions of IE. The code in the expression is saying if this (the image) has a width of greater than 200 pixels then make the width 200px. If you replace "width" with "height" you can fake the max-height property. And of course, if you replace the greater than sign with a less than sign, you can do min-height and min-width.

Of course the real power is in combining max/min height and width to make any image fit into a pre-defined area. How do we achieve tis with expessions? Like this:

#test img {
max-height: 400px;
max-width: 450px;
height: expression(this.height > this.width && this.height > 400 ? 400 : true);
width: expression(this.height < this.width && this.width > 450 ? 450 : true);
}