zoukankan      html  css  js  c++  java
  • 清除float浮动三种方式

    Float的作用?

    w3c的官方解释:

    Content flows down the right side of a left-floated box and down the left side of a right-floated box … Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float didn’t exist.

    看一个例子:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <style>
    .parent {
      background: blue;
      height: 400px;
      color: white;
      font-family: Arial, sans-serif;
    }
    
    .child1 {
      width: 30px;
      height: 30px;
      background: red;
      float: left;
    }
    
    .child2 {
      background: green;
      height: 100px;
    }
    </style>
    </head>
    <body>
      <div class="parent">
        <div class="child1"></div>
        <div class="child2">This text flows around the red box. The green box that holds the text doesn't.</div>
      </div>
    </body>
    </html>
    View Code

    效果如下:

    注意到绿色的box表现的就像红色的box根本不存在一样,但是白色的文字却“浮动”在红色box周围。

    这就是float做的事情:它们导致其他的浮动元素和inline内容浮动在它们周围,但是其他block box却完全不理会float。

    w3c的定义就像是在描述绝对定位元素一样,我更加倾向于将float描述成float是脱离正常流(normal flow)且和兄弟block元素相关的。

    不管怎样解释,你应该知道不论浏览器怎样先进,它们永远不会自动的清除浮动——因为float的行为不是一个bug,而是特点。

    清除浮动的方法

    让我们先说主流的方法:

    clear: both/left/right
    除了“none”以外的任何属性值都将导致元素相应位置不允许浮动。

    overflow: hidden/auto
    float导致了元素坍塌,如果你想让父元素包含所有的float属性元素,那么考虑在父元素上使用overlow:hidden/auto

    clearfix
    最好的方法是使用clearfix属性,下面的代码适用到IE6。

    .clearfix:before,
    .clearfix:after {
        content: " ";
        display: table;
    }
    .clearfix:after {
        clear: both;
    }
    /* For IE 6/7 only */
    .clearfix {
        *zoom: 1;
    }

    如果你想适应IE8及其以上的,只要

    .clearfix:after {
      content: "";
      display: table;
      clear: both;
    }

    你所要做的就是将clearfix类添加到包含floated的父元素上,你当然也可以使用overlow:hidden但是会导致很多布局上的其他问题。

     

  • 相关阅读:
    pwnable.kr login之write up
    安装ubuntu16.4后
    HTML资源定位器-URL
    【实验吧】编程循环&&求底运算
    【SQL注入】mysql中information_schema详解
    C#之BackgroundWorker从简单入门到深入精通的用法总结
    C#使用NPOI对Excel文档进行读、写、导入、导出等操作的dll最新版2.5.1+2.3.0
    Visual Studio中Debug与Release以及x86、x64、Any CPU的区别
    C# 使用BackgroundWorker例子及注意点
    C# BackgroundWorker组件学习入门介绍
  • 原文地址:https://www.cnblogs.com/RachelChen/p/5471033.html
Copyright © 2011-2022 走看看