清除浮动的方法及各自的优缺点

 

float定义使元素脱离文档流,按照指定方向发生移动,遇到父级边界或相邻的浮动元素而停下来。

float特点:

1、块在一行显示

2、内联元素支持宽高

3、默认内容撑开宽高

4、脱离文档流

5、提升层级半层

清除浮动:

clear:left | right | both | none | inherit;元素的某个方向上不能有浮动元素
clear:both;  在左右两侧均不允许浮动元素。
清除浮动的方法:

<div class="box">
    <div class="div1">1222<div>
</div>

css部分:
.box{border:1px solid #ccc;width:400px;}
.div1{width:100px;height:100px;background:red;}

上述例子效果如图:

上述例子中,如果给div1添加float:left;样式,即.div1{width:100px;height:100px;background:red;float:left;}会显现.box包不住.div1的情况,如图:

 如何解决这样的问题呢:
(1)加高度:给父级元素加上高度,即.box{width:400px;height:100px;border:1px solid #ccc;}得到效果:

缺点:这种方法扩展性不好,如果项目的高度是不确定比如瀑布流,这种方法不可行

(2)父级浮动:

问题:页面中所有元素都加浮动,margin左右自动失效

(3)inline-block清浮动方法:

问题:margin左右auto失效

(4)空标签清浮动

<div class="box">
    <div class="div1">11111</div>
    <div class="clearfix"></div>
</div>
.box{border:1px solid #ccc;width:400px;}
.div1{width:100px;height:100px;background:red;float:left;}
.clearfix{clear:both}

问题:在所有有浮动的地方都要加上<div class="clearfix"></div>,增加页面代码冗余;IE6最小高度19px(解决后IE6下还有2px偏差);

(5)<br />清浮动:

 

<div class="box">
    <div class="div1">11111</div>
    <br clear="all" />
</div>

.box{border:1px solid #ccc;width:400px;}
.div1{width:100px;height:100px;background:red;float:left}

 

问题:在所有有浮动的地方都需要加上<br clear="all" />;不符合工作中:结构、样式、行为,三者分离的要求

(6)after伪类清浮动:(现在主流方法)

<div class="box clearfix">
    <div class="div1">11111</div>
</div>

.box{border:1px solid #ccc;width:400px;}
.div1{width:100px;height:100px;background:red;float:left;}
.clearfix::after{
    content:"";  //基于after伪类存在
    height:0;
    clear:both;
    display:block;
}
.clearfix{zoom:1;}

after伪类: 元素内部末尾添加内容;
             :after{content"添加的内容";} IE6,7下不兼容
              zoom 缩放
              a、触发 IE下 haslayout,使元素根据自身内容计算宽高。
              b、FF 不支持;
(7)overflow:hidden清浮动

<div class="box">
    <div class="div1">11111</div>
</div>

.box{border:1px solid #ccc;width:400px;overflow:hidden;}
.div1{width:100px;height:100px;background:red;float:left;}

问题:需要配合 宽度 或者 zoom 兼容IE6 IE7;
        overflow:  scroll | auto | hidden;
        overflow:hidden;溢出隐藏(裁刀!)

BFC (block formatting context)  标准浏览器(chrome、firefox、opera、safari),当出现底下情况任何一种情况时会触发BFC
    a、float的值不为none。
    b、overflow的值不为visible。
    c、display的值为table-cell, table-caption, inline-block中的任何一个。
    d、position的值不为relative和static。
    e、width|height|min-width|min-height:(!aotu)

haslayout      IE浏览器,当出现底下情况任何一种情况时会触发BFC
      a、writing-mode:tb-rl
      b、-ms-writing-mode:tb-rl
      c、zoom:(!normal)

 

posted @ 2017-04-04 16:33  爽朗琴天  阅读(270)  评论(0)    收藏  举报