版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wust_cyl/article/details/85227472
布局1: 高度已知,左边固定,右边自适应
当我们缩小浏览器窗口时,黄色自动缩小
<section>
<article>
<style>
.part2-content-wrap div {
height: 300px;
}
.part2-content-left {
width: 300px;
float: left;
background: red;
}
.part2-content-right {
width: 100%;
background: yellow;
}
</style>
<div class = "part2-content-wrap">
<div class = "part2-content-left"></div>
<div class = "part2-content-right">
<h1>使用浮动方案解决</h1>
<p>高度已知,左边固定,右边自适应</p>
</div>
</div>
</article>
</section>
高度已知,右边固定,左边自适应同理可得!
布局2:高度已知,两边宽度已知,中间自适应
当我们缩小浏览器窗口时,绿色自动缩小
<section>
<article>
<style>
.part1-content-wrap div{
height: 100px;
}
.part1-content-left {
float: left;
width: 300px;
background: red;
}
.part1-content-right {
float: right;
width: 300px;
background: yellow;
}
.part1-content-center {
background: green;
text-align: center;
}
</style>
<div class = "part1-content-wrap">
<div class = "part1-content-left"></div>
<div class = "part1-content-right"></div>
<div class = "part1-content-center">
<h1>使用浮动方案解决</h1>
<p>高度已知,两边宽度已知,中间自适应</p>
</div>
</div>
</article>
</section>
我们来看一下浮动布局带来的问题
看如下代码:
扫描二维码关注公众号,回复:
4957822 查看本文章
<style>
.content-wrap {
width: 500px;
}
.content {
float: left;
width: 120px;
height: 100px;
margin: 0 10px 10px 0;
background: red;
}
.target{
height: 120px;
}
</style>
<div class = "content-wrap">
<div class = "content"></div>
<div class = "content target"></div>
<div class = "content"></div>
<div class = "content"></div>
<div class = "content"></div>
<div class = "content"></div>
<div class = "content"></div>
</div>
不难发现,利用float布局,如果高度不一样,就出现问题了,这也是float布局的重大缺席。
float本身带来的麻烦。
1:使得inline元素block化
<style>
.target{
float:left;
background: red;
width: 50px;
height: 50px;
}
</style>
<span class = "target">6666</span>
2:包裹性
<style>
.content-wrap{
border: 1px solid red;
float: left
}
.target{
width: 60px;
height: 60px;
background: yellowgreen
}
</style>
<div class = "content-wrap">
<div class = "target"></div>
</div>
3:破坏性
因为float元素会脱离文档流(与position: absolute不一样),会导致好像没有高度一样。
<style>
nav div {
height: 100px;
width: 500px;
}
.nav-left{
float: left;
background: red;
}
.nav-right{
float: right;
background: yellow;
}
.content {
height: 500px;
background: green;
}
</style>
<nav>
<div class = "nav-left" ></div>
<div class = "nav-right" ></div>
</nav>
<article>
<div class = "content"></div>
</article>
因为红色和黄色都浮动了,所以绿色就会往上移动。
清除float
1:利用clear属性
2:开启BFC
clear属性
我们之所以能够使用clear解决float引起的父元素塌陷问题,其实就是因为加了clear的空标签或者是那么伪类元素,把top值设置在了浮动元素的bottom边缘下方,从而能够撑起父元素
nav::after{
content: "";
display: table;
clear: both;
}
display:table
;是为了防止子元素垂直方向上的边距折叠,也就是通常说的子元素margin-top会被转移到父元素的问题
父元素开启BFC(google BFC)
nav {
overflow: hidden;
}
也完全没有问题
float布局:兼容性比较好,简单方便,但是也有本身的局限性和float本身带来的问题。
最后提一句:float原本是实现文字环绕效果的,不忘初心。