浮动塌陷

下面的代码会导致浮动塌陷,即par盒子高度为零。

        .par div{background: red;float: left;height: 100px;width: 100px;border: 2px solid blue;}
        </style>
    </head>
    <body>
        <div class="par">//这个盒子高度为零,浮动的两个子盒子不能撑起父盒子的高度
            <div class="div1"></div>
            <div class="div2"></div>
        </div>
    </body>

解决方法:

1.添加一个进行清理的空元素,迫使容器元素包围浮动

缺点是添加不必要的代码,可以利用现成的元素应用clear

        <style>
        .par div{background: red;float: left;height: 100px;width: 100px;border: 2px solid blue;}
        .clear{clear: both;}
        </style>
    </head>
    <body>
        <div class="par">
            <div class="div1"></div>
            <div class="div2"></div>
            <br class="clear"  />  添加空元素进行浮动清除,达到撑开父盒子的目的
        </div>
    </body>

2 让父盒子一起浮动(感觉不好)

  .par{float:left}

3 overflow:hidden;

     缺点是影响框的表现,溢出隐藏。

4 使用css生成内容或js对浮动元素进行清理

css方法:这个方法在ie6不起作用,可以用holly hack来解决。

        <div class="par clear">//添加类名,用来清理
            <div class="div1"></div>
            <div class="div2"></div>
        </div>
.clear:after{
            content: ".";//添加一个点,并将height设为0,通过添加的这个元素进行内容清理
            height: 0;
            visibility: hidden;
            display: block;
            clear: both;
        }

js方法暂不介绍

posted @ 2016-12-01 09:37  党兴明  阅读(273)  评论(0)    收藏  举报