当仅包含浮动项目时,为什么内联块容器不会折叠? [英] Why an inline-block container doesn't collapse when contains only floated items?

查看:42
本文介绍了当仅包含浮动项目时,为什么内联块容器不会折叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此布局中,我将3个框连续地应用到每个框上,每个框应用 float:left; .盒子在另外两个容器中.通常,这些容器会崩溃,因为当内容仅由浮动项目组成时,会发生这种情况.但是,请避免将两个容器的 display 属性更改为 inline-block .

In this layout there are 3 boxes that I'm putting in a row applying float: left; to each one of them. The boxes are inside 2 other containers. Normally, these containers collapse, because that's what happens when the content is only made by floated items. Changing the display property of the 2 containers to inline-block, though, avoid the collapsing.

那是为什么?

另外:我很清楚这样一个事实,我们不应该使用float将元素连续放置,现代而正确的方法是使用 flexbox grid,但是我偶然偶然发现了这个,并且很好奇为什么会这样

Also: I'm well aware of the fact that we shouldn't use float for putting elements in a row and that the modern and correct approach would be to use flexbox or grid, but I've stumbled on this by accident and was curious to understand why

.container {
  background: tomato;
  display: inline-block;
  text-align: center;
  width: 100%;
}

ul {
  background: yellow;
  display: inline-block;
  list-style-type: none;
  padding: 1.5rem;
}

.box {
  border: 3px solid black;
  float: left;
  height: 100px;
  width: 100px;
}

.box-1 {
  background: aquamarine; 
}
.box-2 {
  background: yellowgreen; 
}

.box-3 {
  background: pink; 
}

<div class="container">
  <ul>
  <li class="box box-1"></li> 
  <li class="box box-2"></li> 
  <li class="box box-3"></li> 
  </ul>
</div>

推荐答案

因为 inline-block 生成块格式化上下文

Because inline-block generate a block formatting context

浮点数,绝对定位的元素,不是块框的块容器(例如 inline-block ,表单元格和表标题),以及带有溢出"而不是可见"(除非该值已传播到视口),然后为其内容建立新的块格式设置上下文. 参考

Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents. ref

,您可以阅读 MDN :

格式化上下文会影响布局,但是通常,我们会为定位和清除浮动创建新的块格式化上下文,而不是更改布局,因为建立新块格式化上下文的元素将:

Formatting contexts affect layout, but typically, we create a new block formatting context for the positioning and clearing floats rather than changing the layout, because an element that establishes a new block formatting context will:

  • 包含内部浮点数.
  • 不包括外部浮点数.
  • 禁止利润率下降.

这篇关于当仅包含浮动项目时,为什么内联块容器不会折叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆