清除浮动的方法以及为什么清除浮动

1.为什么清除浮动

   浮动的元素是脱离文档流的元素,其会对父元素以及兄弟元素的布局等产生一定影响

   因此为了避免出现各种样式问题,在使用浮动以后需要进行清除浮动的操作

   下面是没有清除浮动的示例:

   HTML代码:

<ul>
    <li>红色</li>
    <li>绿色</li>
    <li>黄色</li>
</ul>
<div class="next">这是一个测试div</div>

   CSS代码:

ul{
  list-style: none;
  border: 1px solid red;
}
li{
  width: 100px;
  height: 100px;
  float: left;
}
li:nth-child(1){
  background-color: red;
}
li:nth-child(2){
  background-color: green;
}
li:nth-child(3){
  background-color: yellow;
}
.next{
  width:200px;
  height: 200px;
  border: 1px solid black;
}

    效果图:

     

    如上图所示:正常情况下ul作为父元素,在没有设置高度时会被里面的内容撑开,显示出边框或者背景,

    但是由于里面的元素使用了浮动从而脱离了正常文档流,所以边框背景等属性在父元素上不起作用(margin和padding等是可以作用的)

    兄弟元素div.next也没有在正常位置,正常应该再li的下方,但是现在却有一部分被浮动的挡住了。

    为了使父元素和兄弟元素都能够正常显示,下面使用一些方法来清除浮动。

2.清除浮动的一些方法:

   方法一:

   在父元素上添加属性overflow:hidden,此时父元素和兄弟元素都可以正常显示;

   在兄弟元素上添加属性clear:both,此时可以使兄弟元素正常显示在li的下方位置。

   方法二:

    在使用浮动的元素下面增加一个空元素,

     HTML代码:

<ul>
    <li>红色</li>
    <li>绿色</li>
    <li>黄色</li>
    <li></li>
</ul>

    CSS代码:

ul{
    list-style: none;
    margin: 50px;
    border: 1px solid red;
}
li{
    width: 100px;
    height: 100px;
}
li:nth-child(1){
    background-color: red;
    float: left;
}
li:nth-child(2){
    background-color: green;
    float: left;
}
li:nth-child(3){
    background-color: yellow;
    float: left;
}
li:nth-child(4){
    width: 0;
    height: 0;
    clear: both;
}

   (注意不要把最后一个空元素li设置浮动,否则clear:both不起作用)

    该方法也会同时清除父元素和兄弟元素的浮动。

     方法三:

     在父元素上使用:after

      HTML代码:

<ul>
    <li>红色</li>
    <li>绿色</li>
    <li>黄色</li>
</ul>

  CSS代码:

ul{
    list-style: none;
    margin: 50px;
    border: 1px solid red;
    zoom:1;
}
ul:after{
    content: '';
    display: block;
    width: 0;
    height: 0;
    clear: both;
}
li{
    width: 100px;
    height: 100px;
    float: left;
}
li:nth-child(1){
    background-color: red;
}
li:nth-child(2){
    background-color: green;
}
li:nth-child(3){
    background-color: yellow;
}

该方法会同时清除父元素和兄弟元素的浮动。

以上三种方法都可以清除浮动,下面是效果图:
 

  以上是最常见的清浮动的方法,另外在手机端要尽量少使用浮动,亲身经验OTZ

  by新手小白的记录

原文地址:https://www.cnblogs.com/lynnmn/p/6250423.html