zoukankan      html  css  js  c++  java
  • 浮动的清除方式

    在什么时候需要用到浮动呢?

    我们都知道当需要一个左中右三列布局的时候,就需要给左中右的三个div添加float

    添加了浮动有什么影响呢?

     当一个内层元素是浮动的时候,其父元素也就不再包含这个浮动的内层元素,因为此时浮动的元素已经脱离的文档流。这个时候外层的div就无法被撑开,margin也会失效。

    这时候我们就需要清除浮动。。。看下面的demo

    <style>
    .outer{border: 1px solid #ccc;background: #fc9;color: #fff; margin: 50px auto;padding: 50px;  }
    .div1{width: 80px;height: 80px;background: red;float: left;}
    .div2{width: 80px;height: 80px;background: blue;float: left;}
    .div3{width: 80px;height: 80px;background: sienna;float: left;}
    </style>
    <div class="outer">
        <div class="div1">1</div>
        <div class="div2">2</div>
        <div class="div3">3</div> 
    </div>

     这时候我们没有清除浮动,外层的div没有被撑开 ,效果图为:

    第一种方法:给内层元素加一个空的div然后加样式清除

    <style>
    .outer{border: 1px solid #ccc;background: #fc9;color: #fff; margin: 50px auto;padding: 50px;  }
    .div1{width: 80px;height: 80px;background: red;float: left;}
    .div2{width: 80px;height: 80px;background: blue;float: left;}
    .div3{width: 80px;height: 80px;background: sienna;float: left;}
    .clear{clear:both;height:0;} </style> <div class="outer"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div>
    <div class="clear"></div> </div>

     第二种方法:给外层元素加overflow

    <style>
    .outer{border: 1px solid #ccc;background: #fc9;color: #fff; margin: 50px auto;padding: 50px; overflow:hidden;}
    .div1{width: 80px;height: 80px;background: red;float: left;}
    .div2{width: 80px;height: 80px;background: blue;float: left;}
    .div3{width: 80px;height: 80px;background: sienna;float: left;}
    </style>
    <div class="outer">
        <div class="div1">1</div>
        <div class="div2">2</div>
        <div class="div3">3</div>  
    </div>

     第三种方法:利用伪元素after,类似给内层元素添加一个div

    <style>
    .outer{border: 1px solid #ccc;background: #fc9;color: #fff; margin: 50px auto;padding: 50px;}
    .outer:after{content: ''; display: block; clear: both; height: 0; visibility: hidden;}
    .div1{width: 80px;height: 80px;background: red;float: left;} .div2{width: 80px;height: 80px;background: blue;float: left;} .div3{width: 80px;height: 80px;background: sienna;float: left;} </style> <div class="outer"> <div class="div1">1</div> <div class="div2">2</div> <div class="div3">3</div> </div>

  • 相关阅读:
    区块链的入门
    数组元素查找(查找指定元素第一次在数组中出现的索引)
    数组查表法之根据键盘录入索引,查找对应星期
    数组元素反转
    数组获取最大值
    数组的遍历
    数组操作的两个常见小问题越界和空指针
    方法重载练习比较数据是否相等
    方法之根据键盘录入的数据输出对应的乘法表
    方法之根据键盘录入的行数和列数,在控制台输出星形
  • 原文地址:https://www.cnblogs.com/hfxm/p/5588306.html
Copyright © 2011-2022 走看看