Reputation: 10483
Why is it that when I have three boxes in a div without floating them, the outer div wraps around them, but when I add the float, the outer div collapses?
<html>
<head></head>
<body>
<style>
#OuterWrapper {
height: 100%;
width: 200px;
border: 1px BLACK dotted;
text-align: left;
}
.Box {
float: left; // remove this float and the outer wrapper wraps the three boxes
height: 50px;
width: 50px;
background: BLUE;
border: 1px WHITE SOLID;
}
</style>
<div id="OuterWrapper">
<div class="Box"></div>
<div class="Box"></div>
<div class="Box"></div>
</div>
</body>
Upvotes: 1
Views: 118
Reputation: 700262
That is because floating elements doesn't affect the size of the parent element. You can use the overflow
style to make the element contain the children.
Also: You should have a doctype
tag so that the page isn't rendered in Quirks Mode. Your style
element should be in the head
element. The </html>
tag was missing.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<style type="text/css">
#OuterWrapper {
width: 200px;
border: 1px BLACK dotted;
text-align: left;
overflow: hidden;
}
.Box {
float: left;
height: 50px;
width: 50px;
background: BLUE;
border: 1px WHITE SOLID;
}
</style>
</head>
<body>
<div id="OuterWrapper">
<div class="Box"></div>
<div class="Box"></div>
<div class="Box"></div>
</div>
</body>
</html>
Upvotes: 2
Reputation: 29658
You need to clear after the bottom div:
<div style='clear: both'></div>
Using clear: both
will force the outer wrapper div to advance below the last floated box. Here's the full snippet:
<div id="OuterWrapper">
<div class="Box"></div>
<div class="Box"></div>
<div class="Box"></div>
<div style='clear: both'></div>
</div>
Of course, you could also create a helper class in your CSS file:
.ClearBoth {
clear: both;
}
and apply that class to the div after the final box.
Upvotes: 0