美文网首页
理解float

理解float

作者: 可莱恩 | 来源:发表于2017-03-01 22:46 被阅读76次

    一、浮动的设计初衷

    文字环绕效果

    二、 浮动的特性:

    • 包裹(元素)
    • 破坏(父元素的高度)
    2.1 具有包裹性的其它属性
        display : inline-block/table-cell/...
        position: absolute/fixed/sticky
        overflow:hidden/scroll
    
    2.2 具有破坏性的其它属性
        display:none
        position:absolute/fixed sticky
    

    三、文字环绕效果的原理:

    HTML的嵌套关系如下

    div > img
    p

    原理解析:
    1、给img加float:left
    2、img被包裹(inline-block被破坏),并向左靠
    2、div的高度塌陷
    3、p元素的内容得以环绕img

    四、清除浮动

    • 利用clear
    • BFC(IE8+、高级浏览器) / haslayout(IE6、7)
    4.1 利用clear
    • HTML block水平元素底部走起 <div></div>
    • CSS after 伪元素底部生成 .clearfix:after{}

    关于clear的三个值

    凡是clear:left或者clear:right起作用的地方,一定可以使用clear:both替换!
    原因在于,clear属性是让自身不能和前面的浮动元素相邻,注意这里“前面的”3个字,而float属性要么就left要么就right,不可能同时存在。由于clear属性对“后面的”浮动元素不闻不问,因此,当clear:left有效的时候,clear:right必定无效,也就是此时clear:left等同于设置clear:both,反之亦然。
    所以,clear:left和clear:right这两个声明就没有任何使用的价值,至少在CSS世界中是如此,直接使用clear:both吧。
    ----------------------转自 张鑫旭准确理解CSS clear:left/right的含义及实际用途

    通过伪元素使用clear值

    .clearfix:after{
         content:"";
         display:table;
         clear:both
    }
    
    4.2 BFC(IE8+、高级浏览器) / haslayout(IE6、7)

    4.2.1 关于BFC的介绍
    Block Format Content

    简单来说,BFC有三个特性

    • BFC会阻止垂直外边距(margin-top、margin-bottom)折叠
    • BFC不会重叠浮动元素
    • BFC可以包含浮动

    设置方式:

        float:left/right;
        position:absolute/fixed;
        overflow:hidden/scroll(IE7+);
        display:inline-block/table-cell(IE8+);
    

    4.2.2 关于hasLayout
    在IE6、7内有个hasLayout的概念,当元素的hasLayout属性值为true的时候会达到和BFC类似的效果,元素负责本身及其子元素的尺寸设置和定位。我们可以利用这点儿在IE6、7下完成清浮动。

    设置方式:

    width/height/zoom:1/..(IE6/IE7)
    

    4.2.3 靠谱的解决方案

    在IE+、现代浏览器上使用伪元素
    在IE6、7使用hasLayout

    现在常用的方式:

    .floatfix{
        *zoom:1;
    }
    .floatfix:after{
        content:"";
        display:table|block;
        clear:both;
    }
    

    此方案来自以下文章
    The very latest clearfix reloaded
    A new micro clearfix hack

    五:浮动的应用

    两栏自适应布局
    三栏布局

    5.1 两栏自适应布局
        float:left|right;
        display:table-cell;     IE8+
        display: inline-block;    IE7
    
    5.2 三栏布局
    .left{
        background:pink;
        float: left;
        width:180px;
      }
    
     .right{
        background:lightblue;
        width:180px;
        float:right;
      }
    
     .center{
        background:lightyellow;
        overflow:hidden;
        height:116px;
      }
     
    

    其余参考链接
    CSS float浮动的深入研究、详解及拓展(一)
    CSS float浮动的深入研究、详解及拓展(二)
    CSS清浮动处理(Clear与BFC)
    BFC(块级格式上下文)

    相关文章

      网友评论

          本文标题:理解float

          本文链接:https://www.haomeiwen.com/subject/udbcgttx.html