I have a <pre> that I use on my blog to show code samples in, these can get quite long and I want to set a maximum height for them so they don't look messy and take up too much room.

I added:

max-height: 600px;

Which works perfectly on everything I've tested it in, apart from IE6. In IE6 it's as long as the code sample, and has no vertical scrollbar.

Is there an equivalent CSS rule in IE6 for max-height?

3 answers

This was chosen as the best answer

Further to Paul's answer:

CSS expressions are NOT recommended (as per Yahoo! and Google speed/performance advice) as they are executed almost constantly as you use the page.

Instead, the height attribute of the pre should be set on page load by JavaScript:

window.onload = function () {
  var pres = document.getElementsByTagName('pre');
  for (var i = 0, len = pres.length; i < len; i++) {
    pres[i].style.height = (pres[i].scrollHeight > 599) ? "600px" : "auto";

Now the height calculation is only performed once per pre, rather than multiple times.

As you only want this to be applied to IE6, the script should be wrapped in conditional comments, use conditional compilation, or be loaded in an external IE6-only .js file.

Answered over 7 years ago by Matthew Pennell
Tony 25

There is also a CSS only solution to fix the min-height deficiency in IE6:

selector {
  height:auto !important;

Via http://www.dustindiaz.com/min-height-fast-hack/

Answered over 7 years ago by Tony

This is because Explorer 6 (and earlier) doesn't understand max-height, but other browsers do.

There appears to be a workaround for this by using Javascript expressions within your CSS, that only IE understands.

* html pre { 
  height: expression( this.scrollHeight > 599 ? "600px" : "auto" ); /* max-height for IE */
pre {
  max-height: 600px; /* max-height for standards-compliant browsers */

Note that here the "star HTML" hack is being used to serve the first rule only to IE. I'd recommend using a conditional comment instead, as it keeps your IE hacks outside of your main stylesheet.

Answered over 7 years ago by Paul Farnell