A Better Way to Accomplish Min-Something

Do you often find yourself wishing wistfully that you could use min-height or min-width in your css layouts, if only it weren’t for that pesky IE? I have seen many complicated hacks and even scripting solutions to this … but I stumbled on an extremely easy way to use my old friend !important to get the job done with no muss or fuss.

The other day I was faced with a common problem … I needed a box to be at least 200px high, but also needed it to be able to expand as necessary. In Firefox or any other sane browser, I could simply say:

.box {min-height:200px;}

But of course our good friend IE doesn’t recognize the min-whatever properties. So, I hunted around for a solution and came across this article on Mezzoblue. It proposed a pretty complicated solution:

/* for Mozilla/Safari/Opera */
*>.box {
padding-top: 200px;
min-height: 1px;
}
*>.box p {
margin-top: -200px;
}
/* for IE, with IE5/Mac backslash filter \*/
* html .box {
height: 200px;
}
/* end filter */

Wow. Pretty fancy stuff. Unfortunately, and I may have done it wrong, it didn’t work for me. So, I decided to have a go at it on my own. What I came up was this:

.box {
min-height:200px;
height:auto !important;
height:200px;
}

To my great astonishment, this actually worked. See, Firefox and the decent browsers will adhere to the first rule and give a min-height of 200px, while IE will ignore that. Then we set the height to auto and say this is important! FF and company will listen to that, because they obey the important command. Finally, we set the height to 200px; IE will read and follow this value, and by default height in IE works the same way as min-height does in the other browsers. FF and company ignores this final declaration in favor of the important one above it.

Pretty sweet, huh?

3 Responses to “A Better Way to Accomplish Min-Something”

  • David Hucklesby Says:

    Nice, yes.

    With IE7 coming up, with who knows what support for min-height and !important, I have started using conditional comments to give special rules to IE. You can also use them to hide rules from IE, too.

    I do like Stu Nicholls’s method using negative margins to solve min-width in IE (and all other browsers).

    Cordially, David

  • Nancy Perham Says:

    Hi, Mani. Even tho I don’t know html, I thought this was interesting. I think your website is beautiful and I’ll be reading more.

  • Tom Deino Says:

    You know what would be cool? A “Dear Mani” category, where we could send you a bug/question and you can answer it with one of your great Mani solutions…