原因:
元素浮动后,就不在整个文档流的管辖范围,那么它之前存在在父元素内的高度就随着浮动不复存在了,而此时父元素会默认自己里面没有任何内容。
解决方案
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
伪元素解决:
.container {
border: 3px dashed red;
}
.item {
width: 150px;
height: 150px;
}
.item:first-of-type {
background-color: lightgreen;
}
.item:nth-last-of-type(2) {
background-color: lightcoral;
}
.item:last-of-type {
background-color: lightskyblue;
}
.item {
float: left;
}
.container::after {
content: "";
display: block;
clear: both;
}
最简单的解决方案,用到BFC(块级格式化上下文):
.container {
border: 3px dashed red;
}
.item {
width: 150px;
height: 150px;
}
.item:first-of-type {
background-color: lightgreen;
}
.item:nth-last-of-type(2) {
background-color: lightcoral;
}
.item:last-of-type {
background-color: lightskyblue;
}
.item {
float: left;
}
/* .container::after {
content: "";
display: block;
clear: both;
} */
.container {
overflow: auto;
}