
float布局会脱离文档流,对页面的布局造成影响,比如造成父级的高度坍塌等问题。清除浮动后,便不会影响文档流。下面介绍一下现在清除浮动的一些方式。
一、父级添加overflow: hidden;
子元素浮动了,会造成父元素的高度坍塌。只要给父元素添加overflow: hidden;属性,就可以解决浮动带来的影响。
<ul class="cc">
    <li></li>
    <li></li>
</ul>
<style type="text/css">
    li {
        list-style: none;
        height: 100px;
        width: 100px;
        float: left;
        background: red;
        margin-left: 20px;
    }
    
    ul {
        overflow: hidden;
        padding: 0;
        margin: 0;
        background: pink;
    }
</style>二、通过属性clear:both;达到清除浮动的目的;
元素浮动后,只需要在浮动元素添加多一个块级元素,并添加clear: both;属性,便可以达到清除浮动的目的。
<style type="text/css">
    li {
        list-style: none;
        height: 100px;
        width: 100px;
        float: left;
        background: red;
        margin-left: 20px;
    }
    ul{
        background: pink;
    }
</style>
<ul class="cc">
    <li></li>
    <li></li>
    <div style="clear: both;"></div>
</ul>三、通过给父级元素添加伪类after,达到清除浮动的目的;
这种方式也是使用clear: both;的方式达到效果,只是变相的使用了伪类after,使得页面结构更简洁,也是常用的清理浮动的方式。
<style type="text/css">
    li {
        list-style: none;
        height: 100px;
        width: 100px;
        float: left;
        background: red;
        margin-left: 20px;
    }
    .cc:after {
        content: '';
        height: 0;
        line-height: 0;
        display: block;
        visibility: hidden;
        clear: both;
    }
    ul{
        background: pink;
    }
</style>
<ul class="cc">
    <li></li>
    <li></li>
</ul>四、使用双伪类;
此方式和三原理一样,代码更简洁。
<style type="text/css">
    li {
        list-style: none;
        height: 100px;
        width: 100px;
        float: left;
        background: red;
        margin-left: 20px;
    }
    
    .cc:after,
    .cc:before {
        content: "";
        display: block;
        clear: both;
    }
    
    ul {
        background: pink;
    }
</style>
<ul class="cc">
    <li></li>
    <li></li>
</ul>以上就是css清除浮动有几种方法?的详细内容,更多请关注易知道|edz.cc其它相关文章!












