为什么内联块容器在仅包含浮动项时不会折叠?

Why an inline-block container doesn't collapse when contains only floated items?

在此布局中,我将 3 个框排成一行,对每个框应用 float: left;。 这些盒子在另外 2 个容器内。通常,这些容器会倒塌,因为当内容仅由浮动项目构成时就会发生这种情况。 将 2 个容器的 display 属性 更改为 inline-block,但是,避免折叠。

这是为什么?

另外:我很清楚我们不应该使用 float 来将元素放在一行中,现代和正确的方法是使用 flexboxgrid , 但我无意中发现了这一点,很想知道为什么

.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生成块格式化上下文

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

您可以阅读 the 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:

  • contain internal floats.
  • exclude external floats.
  • suppress margin collapsing.