css清除浮动各类方法:

1,在浮动元素后面增长<br/>标签;浏览器

  <br/>标签有自带的清除浮动属性;code

2,在浮动元素后面增长一个清除浮动层;orm

  <div>

    <div style="float:left"></div>

    <div style="float:left"></div>

    <div style="clear:both"></div>

  </div>

3,给浮动元素添加overflow:auto样式;文档

4,为最后浮动元素设置以下样式:it

  

/* 清理浮动 */
    .clearfix:after {
     visibility:hidden;
     display:block;
     font-size:0;
     content:" ";
     clear:both;
     height:0;
    }
    .clearfix {
     zoom:1;
    }

其原理是,在「高级」浏览器中使用 :after 伪类在浮动块后面加上一个非 display:none 的不可见块状内容来,并给它设置 clear:both 来清理浮动。在 ie6 和 7 中给浮动块添加 haslayout 来让浮动块撑高并正常影响文档流。

5,另外一种简洁的办法:table

.cf:before, .cf:after {
        content:"";
        display:table;
    }
    .cf:after {
        clear:both;
    }
    .cf {
        zoom:1;
    }

原理仍是同样的。使用 :after 伪类来提供浮动块后的 clear:both。不一样的是,隐藏这个空白使用的是 display: table。而不是设置 visibility:hidden;height:0;font-size:0; 这样的 hack。

值得注意的是这里中的 :before 伪类。其实他是来用处理 top-margin 边折叠的,跟清理浮动没有多大的关系。但由于浮动会建立 block formatting context,这样浮动元素上的另而一元素上若是恰好有 margin-bottom 而这个浮动元素恰好有margin-top 的话,应该让他们不折叠(虽然这种状况并不常见)。
相关文章
相关标签/搜索