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

问题描述

在此布局中,我将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

,您可以阅读 MDN :

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

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

08-31 02:18