CSS Hackz Series: Minimum Width, Maximum Width for Internet Explorer 6

Opening the CSS Hackz series is the infamous CSS-expression hack for achieving minimum and maximum widths in Internet Explorer 6.

Here is how to set the maximum width for IE 6:

#target_element { 	
	width: expression((document.body.clientWidth > 778)? "777px" : "auto");
	max-width: 777px;
	}

Here is how to set the minimum width for IE 6:

#target_element { 	
	width: expression((document.body.clientWidth < 335)? "333px" : "auto");
	min-width: 333px;
	}

Here is how to set both maximum and minimum widths for IE 6:

#target_element { 	
	width: expression((document.body.clientWidth < 335)? "333px" : (document.body.clientWidth > 778)? "777px" : "auto");
	max-width: 333px;
	min-width: 777px;
	}

To implement any of these techniques, simply replace all instances of 777 and/or 333 with the desired target min/max width(s). Then replace all instances of 778 and/or 335 with a value that is at least one pixel greater than your target value(s). This important step is frequently omitted from many min/max-width tutorials, and is required to prevent Internet Explorer from freezing up and crashing. See this comment for additional information.

Alternatively, as Robert Nyman points out, a better approach involves targeting IE 6 directly via externally executed JavaScript function:

window.onload = checkAvailableWidth;
window.onresize = checkAvailableWidth;
function checkAvailableWidth(){
	var container = document.getElementById("container");
	container.style.width = (document.body.clientWidth > 1100)? "1100px" : "auto";
}

..which should be included via conditional comment:

<!--[if lt IE 7]>
	<script type="text/javascript" src="/js/maxWidthFixForIE6.js"></script>
<![endif]-->

There are several clear benefits to using this method for achieving minimum and maximum widths in IE 6:

  1. Valid CSS!
  2. Clean separation of behavior from presentation
  3. Vastly improved performance due to JavaScript’s use of event handlers. The CSS expression is recalculated continuously as the user interacts with the web page, while the JavaScript behavior is calculated only when the specified events (i.e., browser resize) occur.

Either way, it’s your choice which method to use when implementing minimum/maximum width for IE 6. If you know of an alternate method of achieving the effect, be kind and share a comment with us!

Next up..

Next in the CSS Hackz Series: PNG Image Display for Internet Explorer! Don’t miss it!