美文网首页
清除float的方法

清除float的方法

作者: 郭先生_515 | 来源:发表于2019-02-19 14:22 被阅读0次
为什么要清除float?

因为浮动是使用了float:left或float:right或两者都有而造成的样式缺失或者不正确显示等问题。
浮动不属于文档流中的普通流,当元素浮动之后,不会影响块级元素的布局,只会影响内联元素布局。

由于浮动产生,如果对父级设置了【CSS background背景】【CSS背景颜色】或【CSS背景图片】,因为父级不能被撑开,所以导致CSS背景不能显示。

首先写一个小demo:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>float</title>
    <style>
        .box{
            margin: 50px auto;
            border: 1px solid #ccc;
            background: yellow;
            color: #fff;
        }
        .red{
            width: 80px;
            height: 100px;
            background: red;
            float: left;
        }
        .green{
            width: 80px;
            height: 100px;
            background: green;
            float: left
        }
        .blue{
            width: 80px;
            height: 100px;
            background: blue;
            float: left;
        }
    </style>
</head>
<body>
<body>
    <div class="box">
        <div class="red">1</div>
        <div class="green">2</div>
        <div class="blue">3</div>
    </div>
</body>
</body>
</html>

造成的问题:由于子元素都设置了float属性,父元素div高度不能撑开,所以父元素的背景无法显示。

解决方案:

  1. 父元素内尾部添加元素clear
html:
<div class="clear"></div>

<style>
.clear{
 clear: both;
}
</style>

2.父元素添加属性

<style>
.box {
  overflow: auto;    
}
</style>

3.父盒子使用伪类after清除float(推荐使用这种写法)

.box:after {
    display: block;
    visibility: hidden;
    clear: both;
    content: "";
}
.box{
    zoom:1;/*解决兼容问题*/
}

4.使用双伪类before和after

.box:before,.box:after {
    display: block;
    clear: both;
    content: ''
}
.box {
    zoom: 1; 
}

相关文章

网友评论

      本文标题:清除float的方法

      本文链接:https://www.haomeiwen.com/subject/ukoxyqtx.html