css - 为什么内联 block 和 block 在 float 元素附近表现不同?

标签 css css-float

我注意到内联 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
}

enter image description here

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
}

enter image description here

有解释吗?

最佳答案

我假设您了解 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/

相关文章:

javascript - 为什么我的过渡动画在关闭 div 时出现故障?

javascript - 如何响应 "shown.bs.collapse"事件?

css - 将背景图像放置在 ul/li 元素的边缘之外

css - 将站点表单表格转换为 div

css - 滚动 DIV 后 float 一个 DIV

html - 两个 float 列 - 一个固定,一个松散宽度

html - 具有 3 个嵌套列表的 CSS 菜单 - 左对齐问题

javascript - 自定义中断词

html - float 的 div,最大宽度不起作用

jquery - 使用 jQuery 以百分比形式设置 outerWidth