当我们在css中使用float时,为什么我们会失去父样式



我知道float不再被使用,而是被flex所取代,但我只是想知道为什么它在实现时会失去父样式。

示例:

h1 {
margin: 0;
}
.container {
background-color: tan;
}
.one,
.two,
.three {
float: left;
width: 300px;
height: 200px;
text-align: center;
padding: 7px;
background-color: thistle;
border: 1px solid slategrey;
}
<div class="container">
<div class="one">
<h1>Section 1</h1>
</div>
<div class="two">
<h1>Section 2</h1>
</div>
<div class="three">
<h1>Section 3</h1>
</div>
</div>

在上面的例子中,容器div的背景色在实现float后就不起作用了!

这是因为您已将'display:foat'分配给的元素现在是浮动。它们是在正常文档流之外获取的。

如果您仍然想使用float,则需要使用clear

h1 {
margin: 0;
}
.container {
background-color: tan;
}
.clearfix:after {
content: "";
display: table;
clear: both;
}
.one,
.two,
.three {
float: left;
width: 300px;
height: 200px;
text-align: center;
padding: 7px;
background-color: thistle;
border: 1px solid slategrey;
}
<div class="container clearfix">
<div class="one">
<h1>Section 1</h1>
</div>
<div class="two">
<h1>Section 2</h1>
</div>
<div class="three">
<h1>Section 3</h1>
</div>
</div>

但不建议使用float进行布局设计。你可以在这里阅读更多关于它的信息:什么是clearfix?。

相关内容

最新更新