css清除浮动定位造成的异常

清除浮动是为了解决高度塌陷的问题:内层有好几个div有宽有高,并且选择了浮动定位,但是外层的div却并没有设置宽高。在非IE浏览器(如Firefox)下,当容器的高度为auto,且容器的内容中有浮动(float为left或right)的元素,在这种情况下,容器的高度不能自动伸长以适应内容的高度,使得内容溢出到容器外面而影响(甚至破坏)布局的现象。这个现象叫浮动溢出,为了防止这个现象的出现而进行的CSS处理,就叫CSS清除浮动。

没有清除浮动前:高度为0

清除浮动后:有了高度

 

常见解决方案:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
    *{
        padding: 0;
        margin: 0;
        border: 0;
        outline: 0;
    }
    p{
        line-height: 150%;
    }
    /*清除浮动方法3 全局 for FF/chrome/opera/IE8== */
    :after {clear:both;content:'.';display:block;width: 0;height: 0;visibility:hidden;}  

    .test{
        
        background: rgb(164, 206, 188);
        margin: 0 auto;
        width: 150px;

        /*清除浮动方法2  clear:overflow*/
        /*height: auto;
        overflow: auto;
        zoom:1;*/
    }
    .div1{
        float:left; 
        width:50px;
        height:50px;
        text-align: center;
        line-height: 50px;
        border-bottom: 1px #ddd solid;
    }
</style>
<body>

    <div class="test">
        <div class="div1">1</div>
        <div class="div1">2</div>
        <div class="div1">3</div>
        <!-- 清除浮动方法1  clear:both -->
        <!-- <div style="clear:both;"></div> -->
    </div>

</body>
</html>

 

 

当然,你也可以直接给外层加个宽高 == 简单粗暴又有效

或者,内层选择html5的分列显示,也是很好的方案

再或者,直接用一些框架的栏栅结构

 

posted @ 2016-04-13 15:51  Cynthia娆墨旧染  阅读(2843)  评论(0编辑  收藏  举报