CSS - 为什么不使用 float 时容器中的框?

标签 css css-float

为什么当我在一个 div 中有三个盒子而不 float 它们时,外面的 div 环绕它们,但是当我添加 float 时,外面的 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>

最佳答案

那是因为 float 元素不会影响父元素的大小。您可以使用 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>

关于CSS - 为什么不使用 float 时容器中的框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7374177/

相关文章:

html - @font-face 的 CSS 问题

html - 非 float div 的内部文本相对于前一个 float div 定位

html - 使 <ul> 列表响应 - 最后一个 <li> 不向左浮动

html - 如何使div先垂直堆叠然后水平堆叠?

css - Sass 文件不能在 IE 上运行

css - react native 图像不显示

html - 垂直对齐未知高度的 float 元素

html - 在表单中的标签中添加 CSS float 使背景颜色消失

javascript - Safari 不允许与输入的密码交互,同时允许输入到其他输入字段

css - 选中时无法更改 Font Awesome 图标颜色 - 复选框