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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…