为什么当我在div中有三个盒而没有浮动它们时,外部div包围它们,但是当我添加浮动时,外部div会崩溃?
<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>
答案 0 :(得分:2)
这是因为浮动元素不会影响父元素的大小。您可以使用overflow
样式使元素包含子元素。
另外:您应该有一个doctype
标记,以便页面不会以Quirks模式呈现。您的style
元素应位于head
元素中。 </html>
标记丢失了。
<!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>
答案 1 :(得分:0)
您需要在底部div之后清除:
<div style='clear: both'></div>
使用clear: both
将强制外包装div在最后一个浮动框下方前进。这是完整的片段:
<div id="OuterWrapper">
<div class="Box"></div>
<div class="Box"></div>
<div class="Box"></div>
<div style='clear: both'></div>
</div>
当然,您也可以在CSS文件中创建一个帮助器类:
.ClearBoth {
clear: both;
}
并在最后一个框之后将该类应用于div。
答案 2 :(得分:0)
尝试将overflow:hidden;
样式添加到包装器div。