zoukankan      html  css  js  c++  java
  • 学习经常遇到的浮动(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并排显示,但只能是从左向右。

  • 相关阅读:
    在 Java 中遍历 HashMap 的5种最佳方式
    Java 8 Stream.reduce() 使用示例
    Redis 为什么这么快?
    java8 常用代码
    为什么我们越娱乐反而会越无聊?
    Arrays.sort() VS Arrays.parallelSort()
    Java中枚举类型Enum的一种使用方式
    An illegal reflective access operation has occurred
    多线程中常见锁概述
    Java中创建多线程的三种方式
  • 原文地址:https://www.cnblogs.com/zhuxingqing/p/11131041.html
Copyright © 2011-2022 走看看