这是我参与「4月日新计划更文活动」的第10天。
我们今天讲一下如何清除浮动的方法。
从使用上来拆分,一共可以分成4种方法。
方法一:给父类添加overflow:hidden属性清除浮动。
方法二:给父类的最后一个元素或者伪类添加clear: both属性清除浮动。
方法三:给父类添加display:flex或display:inline-flex属性清除浮动。
方法四:给父类添加display:grid或display:inline-grid属性清除浮动。
好,我们一个个的来看。
方法一:给父类添加overflow:hidden属性清除浮动
效果展示如下:
代码如下:
<style>
.container{
width: 100%;
overflow: hidden;
}
.left{
float: left;
width: 30%;
height: 300px;
background-color: aquamarine;
text-align: center;
font-size: 36px;
line-height: 300px;
color: #fff;
}
.right{
float: left;
width: 70%;
height: 300px;
background-color: bisque;
text-align: center;
font-size: 36px;
line-height: 300px;
color: #fff;
}
</style>
<body>
<div class="container">
<div class="left">左边</div>
<div class="right">右边</div>
</div>
</body>
方法二:给父类的最后一个元素或者伪类添加clear: both属性清除浮动
展示效果跟上面一样。
代码如下:
<style>
.container{
width: 100%;
}
.container:after{
content: '';
display: block;
clear: both;
}
.left{
float: left;
width: 30%;
height: 300px;
background-color: aquamarine;
text-align: center;
font-size: 36px;
line-height: 300px;
color: #fff;
}
.right{
float: left;
width: 70%;
height: 300px;
background-color: bisque;
text-align: center;
font-size: 36px;
line-height: 300px;
color: #fff;
}
</style>
<body>
<div class="container">
<div class="left">左边</div>
<div class="right">右边</div>
</div>
</body>
方法三:给父类添加display:flex或display:inline-flex属性清除浮动
展示效果跟上面一样。
代码如下:
<style>
.container{
width: 100%;
display: flex;
display: inline-flex;
}
.left{
float: left;
width: 30%;
height: 300px;
background-color: aquamarine;
text-align: center;
font-size: 36px;
line-height: 300px;
color: #fff;
}
.right{
float: left;
width: 70%;
height: 300px;
background-color: bisque;
text-align: center;
font-size: 36px;
line-height: 300px;
color: #fff;
}
</style>
<body>
<div class="container">
<div class="left">左边</div>
<div class="right">右边</div>
</div>
</body>
方法四:给父类添加display:grid或display:inline-grid属性清除浮动
展示效果跟上面一样。
代码如下:
<style>
.container{
width: 100%;
display: grid;
display: inline-grid;
}
.left{
float: left;
width: 30%;
height: 300px;
background-color: aquamarine;
text-align: center;
font-size: 36px;
line-height: 300px;
color: #fff;
}
.right{
float: left;
width: 70%;
height: 300px;
background-color: bisque;
text-align: center;
font-size: 36px;
line-height: 300px;
color: #fff;
}
</style>
<body>
<div class="container">
<div class="left">左边</div>
<div class="right">右边</div>
</div>
</body>
以上就是我今天学习和整理的清除浮动的方法。
看到掘金上的好文章,如果对你有帮助,顺手点个赞,或者把文章收藏。不用担心找不到了,以后也能经常收到类似好回答,我会持续进行更新。