• 学习经常遇到的浮动(float)


    参考自 小辉随笔:

    https://www.cnblogs.com/lchsirblog/p/9582989.html

    一、什么时候需要使用浮动

    最常见的情景是:多个块级元素(如div)需要同一行显示。

    <div class="data-float-parent">
        <div class="data-float-child1"></div>
        <div class="data-float-child2"></div>
    </div>

    如上,如要要求 child1 和 child2 同行显示,需要给这两个 div 的样式设置 float: left; ,在父元素没有高度的前提下,会导致父元素高度塌陷。

     如果能确定父元素高度,给一个 height 值就可以解决。

    二、清除浮动

    (1)在父元素的最后加一个冗余元素并为其设置 clear:both

    <div class="data-float-parent">
        <div class="data-float-child1"></div>
        <div class="data-float-child2"></div>
        <div class="clear"></div>
    </div>
           .data-float-parent{
                width: 200px;
                /*height: 200px;*/
                border: 1px solid red;
            }
            .data-float-child1{
                width: 100px;
                height: 100px;
                float: left;
                background-color: green;
            }
            .data-float-child2{
                width: 100px;
                height: 100px;
                float: left;
                background-color: orange;
            }
            .clear{
                clear: both;
            }

    缺点:很明显冗余元素不符合语义化

    (2)使用伪元素 :after ,添加一个类 clearfix(荐)

    <div class="data-float-parent clear-float">
        <div class="data-float-child1"></div>
        <div class="data-float-child2"></div>
    </div>
         .clear-float:after{
                content: "";
                display: table; /*采用此方法可以有效避免浏览器兼容问题*/
                clear: both;
            }

    这是推荐的做法,但 :after 在 IE6/IE7 不兼容

    (3)父元素 BFC(IE8) 或 haslayout(IE6/IE7)

         .clear-float{
                overflow: hidden;
                zoom: 1;
            }
            /* zoom:1; 兼容IE6 */

    注:display:inline-block 也可以实现多个div并排显示,但只能是从左向右。

  • 相关阅读:
    睁大你的眼睛,警惕职业生涯中的“红灯”
    几则好玩的脑筋急转弯
    File.Delete()的解决
    Powershell之True或False
    发送邮件
    IE与CSS兼容性
    WSS
    File.Delete()
    添加field部署
    css加载
  • 原文地址:https://www.cnblogs.com/zhuxingqing/p/11131041.html
Copyright © 2020-2023  润新知