Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

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

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.

Why is that?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because inline-block generate a block formatting context

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

and you can read in 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...