我注意到内联 block 和 block 位于 float 元素附近时表现不同: block 的背景延伸到 float 元素下方,而内联 block 将其完全包裹起来。
div
是一个 block :
div {
height: 5em;
width: 5em
}
div:first-child {
background: #27A5CC;
float: left
}
div:nth-child(2) {
width: 6em;
background: #EEEEEE
}
div
是一个内联 block :
div {
height: 5em;
width: 5em
}
div:first-child {
background: #27A5CC;
float: left
}
div:nth-child(2) {
width: 6em;
background: #EEEEEE;
display: inline-block
}
有解释吗?
最佳答案
我假设您了解 block
之间的区别和 inline-block
显示。现在让我们看看如何floats
工作:
A float is a box that is shifted to the left or right on the current line. [...] Content flows down the right side of a left-floated box and down the left side of a right-floated box.
A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float. If there is a line box, the outer top of the floated box is aligned with the top of the current line box. [...]
Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.
你的例子解释如下:
示例 1
第一个 div 是 float 的。它从流中取出并与父元素的左侧对齐。第二个 div 也从左侧开始忽略第一个 div,就好像它不存在一样。
结果:两个 div 的左上角最终彼此对齐。
示例 2
第一个 div 是 float 的。它从流中取出并与父元素的左侧对齐。第二个 div 是一个内联 block 元素,因此它遵循适用于内容流和行框的规则。它开始向第一个 div 的右侧呈现就像普通文本一样。
结果:第二个 div 与第一个 div 的右侧对齐。
关于css - 为什么内联 block 和 block 在 float 元素附近表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25460463/