Sometimes designing a website requires you to limit the dimensions of a dynamically sized element without specifying an explicit width or height. CSS defines four basic attributes with which we can control such a behaviour:
- min-width: defines the lower limit of width for the element
- max-width: defines the upper limit of width for the element
- min-height: same as min-width, only for height
- max-height: same as max-width, only for height
Using these attributes will work on all current browsers, but as always, Internet Explorer 6 dissapoints – it doesn't support the above attributes, thus ignoring any constraints.
The solution comes with a proprietary feature in IE's CSS engine – CSS expressions. Basically, they're Javascript expressions that you can use to set CSS attribute values. They are not part of the official CSS spec and will present themselves as errors to online validators, though.
As an example, let's take a simple <div> element we'd like to constrain the width dimension between 300px and 600px. It can be anywhere in the range of these two values, but not outside the range:
<div id="expando">
Lorem ipsum dolor sit amet
</div>
The standard CSS would look like the following:
#expando { min-width: 300px; max-width: 600px; }
To apply the CSS expression to the same element, we put in the following CSS declaration:
#expando {
width: expression((expando.clientWidth > 600? 600 : (expando.clientWidth < 300? 300 : expando.clientWidth)) + "px");
}
This way, we've clamped down on the values using an expression, which is basically just Javascript that recalculates the width during the measuring phase.
Be warned though – this expression is evaluated whenever IE executes the measure phase of document redraw. In a complex and dynamic layout, this could dramatically slow down the page and cause spikes in CPU usage.
To limit this expression to IE6 and under (since later version support min-* and max-*), we put it in a separate CSS file and include it in the document using a conditional HTML comment inside the <head> element:
<!--[if lte IE 6]> <link rel="stylesheet" type="text/css" href="ie6.css"/><![endif]-->
That way, we only serve the CSS file to IE6 or earlier, thereby circumventing all other browsers and still validating the CSS.