html - 在一个未指定高度和一个清晰的div的两列边框框中,是什么导致了高度差异?

标签 html css css-float

我创建了一个 JSFiddle说明示例,并将在本文末尾包含 HTML/CSS。我对 border-box 样式选项的理解是,它会导致在指定 宽度和高度中包含边框和填充。在示例中,我使用了最小高度,因此右侧的框会随着额外的填充而增加高度,但不会增加宽度。

第二个例子中额外的高度来自哪里?首先,使用两个宽度相等且高度保持不变的 float 。在第二个中,右边的高度随着填充而增加。只有在嵌套框内放置清晰的 div 时才会发生这种情况。删除清晰的 div 会导致第二个示例看起来相同,但我不明白为什么清晰的 div 会导致额外的高度。

更新:

出于某种原因,将 overflow 设置为 hidden on the boxes 解决了这个问题,没有任何奇怪的行为。我不知道为什么。

HTML:

<div id="correct">
    <div class="box"><div style="clear: both;"></div></div>
    <div class="box"><div style="clear: both;"></div></div>

    <div style="clear: both;"></div>
</div>

<div id="incorrect">
    <div class="box"><div style="clear: both;"></div></div>
    <div class="box"><div style="clear: both;"></div></div>

    <div style="clear: both;"></div>
</div>

关联的 CSS:

* { box-sizing: border-box; }

#correct,
#incorrect {
    width: 800px;
    border: 1px solid red;
    padding: 5px;
    margin-bottom: 10px;
}

.box {
    min-height: 100px;
    width: 50%;
    border: 1px solid green;
    padding: 10px;
}

#correct .box {
    float: left;
}

#incorrect .box:nth-of-type(1) {
    float: left;
}

#incorrect .box:nth-of-type(2) {
    margin-left: 50%;
}

最佳答案

如前所述,这与 box-sizing: border-box 无关。您的理解是正确的,因为 box-sizing 计算仅适用于具有指定高度的框,而这里不是这种情况。

发生这种情况是因为第二个框(具有额外高度)内的 clearfix 试图清除它旁边的 float 。这会导致 clearfix 被一直向下推,使其与 float 的底部边界齐平。 Section 9.5.2 of the spec详细描述了清除行为,解释了许多情况,但它归结为尽可能多地向下移动 clearfix 以“将 [clearing element] 的边界边缘放置在最低 float 的底部外边缘那是要清除的。”

额外高度只是非 float 框的底部填充 — clearfix 不能渗入 填充区域,因此框必须扩大其内容区域以适应 clearfix 的新位置.

如果您向 clearfixes 添加一些内容,you can see where exactly each one is being rendered :

div[style]::before {
    content: 'clearfix';
}

如果您为框指定高度,that clearfix will overflow the box作为尝试清除 float 框的结果(无论 box-sizingcontent-box 还是 border-box,都会发生这种情况,尽管它确实会影响高度计算本身):

.box {
    height: 100px;
    width: 50%;
    border: 1px solid green;
    padding: 10px;
}

删除 clearfix 解决问题的原因是因为没有任何间隙,第二个盒子中没有任何东西可以移动,所以它的高度不会增加。

float 两个盒子设置overflow: hidden 解决问题的原因是因为这些事情中的每一个都会导致盒子建立自己的block formatting contexts . BFC 的定义特征之一是它外部的 float 永远不能与它内部的任何元素交互。这包括 BFC 中的所有 clearfix 框。

不设置 overflow 属性或 float 第二个框,

  1. float 框(#incorrect .box:nth-of-type(1)),
  2. 非 float 框(#incorrect .box:nth-of-type(2))
  3. 它的 clearfix (#incorrect .box:nth-of-type(2) div[style])

都参与同一个 block 格式化上下文。正是由于这个原因,非 float 框中的 clearfix 试图清除 float 框。 (再次注意, float 框内的clearfix参与的是 float 框建立的BFC,不是以上三个元素参与的,建立的通过 initial containing block .)

关于html - 在一个未指定高度和一个清晰的div的两列边框框中,是什么导致了高度差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28949120/

相关文章:

html - Flex - 图像约束

html - GridView 中的单选按钮

html - 如何使响应圈 <div> 中的文本也响应

javascript - 我的联系表单验证的小错误。电子邮件验证与我的其余代码纠缠不清

html - 在包装器中并排放置 2 个 div 时遇到问题

javascript - 将 javascript 生成的图像复制到剪贴板

javascript - 如何在不更改主文件的情况下撤消 Core.JS 代码?

javascript - 计算文本区域中文本的大小

html - 在 table-cell 元素中使用 float 属性将先前的内容向下滑动

css - Div 不随内容扩展