Making outer DIV's height change depending on inner elements

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Making outer DIV's height change depending on inner elements

Post by jayshields »

Right, I've had this problem numerous times, and I always end up hacking around it, usually by setting the outer DIV height attribute to accomodate the inner (inline) elements, but this is getting out of hand now.

Example:

Code: Select all

<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>Blah</title></head>
<body>
<div style="border: 1px solid #000; padding: 20px; margin: 20px; background-color: green;">
	<p style="margin: 0px; padding: 0px;">Outer DIV</p>
	<span style="float: left; border: 1px solid #000; padding: 0px; margin: 0px; background-color: red;">
		Inner DIV<br />
		Inner DIV<br />
		Inner DIV<br />
		Inner DIV<br />
		Inner DIV<br />
		Inner DIV<br />
		Inner DIV<br />
		Inner DIV<br />
		Inner DIV
	</span>
</div>
</body>
</html>
http://www.jay-designs.co.uk/test/example.html

Basically I want the outer DIV's height to change depending on what the inner elements height is; I don't want the inner element to spill out of the outer one. I've tried numerous position attributes on both the said elements with no luck.

I hope I won't have to use JavaScript for this, and I'm sure one of you guys knows how to change the CSS to get this how I want!

Thanks.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

As soon as you apply position, the boxes will overflow their boundaries. This is the way the box-model was written. Add a <div> with clear:both set.

Code: Select all

<head><title>Blah</title></head> 
<body> 
<div style="border: 1px solid #000; padding: 20px; margin: 20px; background-color: green;"> 
        <p style="margin: 0px; padding: 0px;">Outer DIV</p> 
        <span style="float: left; border: 1px solid #000; padding: 0px; margin: 0px; background-color: red;"> 
                Inner DIV<br /> 
                Inner DIV<br /> 
                Inner DIV<br /> 
                Inner DIV<br /> 
                Inner DIV<br /> 
                Inner DIV<br /> 
                Inner DIV<br /> 
                Inner DIV<br /> 
                Inner DIV 
        </span>
        <div style="height: 0; clear: both;"></div>
</div> 
</body> 
</html>
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

Great, I will try that when I get back home. Thanks :)
Post Reply