tags:

views:

2029

answers:

3

I have a very simply problem where I need a div to expand to fit its contents unless the height reaches a certain size, when I want the div to scroll vertically instead. As a test, I created a page containing:

<div style="width:300px;max-height:25px;background-color:green;overflow:auto;">
    1<br />
    2<br />
    3<br />
    4<br />
    5
</div>

Unfortunately, the max-height doesn't seem to work. What am I doing wrong?

I am using IE7.

+1  A: 

Here's the cross-browser way to set min-height:

min-height: 400px;
height:auto !important;
height:400px;

IE treats the height attribute as min-height, and ignores min-height.

Edit: Misread the question as min-height! (>_<)

tj111
Will this fix the max height problem?
David Basarab
Not as far as I'm aware. I think you need to use CSS expressions (ugh) or javascript to fix max-height. This only works because IE treats height as min-height, and will use the last rule to appear, so it ignores the 'auto'. If you get it to work though I would love to know :).
tj111
+3  A: 

The problem is your browser. Maybe you could wrap this div in another div that has the fixed height of 25px. Of course this wouldn't be exactly the same as max-height.

An article about a solution.

Edit: According to Microsoft it should work in IE7+.

Have you set an appropriate doctype? If not IE7 uses an old layout engine. You should use HTML 4 or XHTML.

Georg
Brilliant, thanks!
Baffled by ASP.NET
+2  A: 

Your code works for me.

When I wrap it with a page!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>1 2 3 4 5</title>
</head>

<body>
<div style="width:300px;max-height:25px;background-color:green;overflow:auto;">
    1<br />
    2<br />
    3<br />
    4<br />
    5
</div>
</body>

</html>

Works in IE7 and Chrome fine.

FF3 is not giving me scrolls bars.

But the max height works fine in all three.

Without the surrounding page though your snippet of code does not work. I suggest testing code in a valid page of HTML. * grins *

Iain M Norman
That's because of the doctype you have. Unfortunately I can't use that doctype because it interferes with the control set that we use.
Baffled by ASP.NET
What doctype do you need to use, I'll fiddle with that.
Iain M Norman
Worked out the FireFox issue, the max-height is too small for the scroller chrome, causing it to dissapear.
Iain M Norman
I need no doctype. As soon as I set a doctype, the control set goes screwy - mainly because it uses tables for layouts that exhibit the same problem.
Baffled by ASP.NET