4 common ways to clear floating (front-end interview questions)

Floating elements leave the document flow and do not take up space. The floating element touches the border containing it or the border of the floating element stays.

1. Use an empty label to clear the float.

This method is to add an empty tag definition css clear:both after all floating tags. The disadvantage is that it adds meaningless tags.


```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    .fahter{
     
     
        width: 400px;
        border: 1px solid deeppink;
    }
    .big{
     
     
        width: 200px;
        height: 200px;
        background: darkorange;
        float: left;
    }
    .small{
     
     
        width: 120px;
        height: 120px;
        background: darkmagenta;
        float: left;
    }
    .footer{
     
     
        width: 900px;
        height: 100px;
        background: darkslateblue;
    }
    .clear{
     
     
        clear:both;
    }
    </style>
</head>
<body>
    <div class="fahter">
        <div class="big">big</div>
        <div class="small">small</div>
        <div class="clear">额外标签法</div>
    </div>
    <div class="footer"></div>
</body>
</html>
2.使用after伪对象清除浮动

 该方法只适用于非IE浏览器。具体写法可参照以下示例。使用中需注意以下几点。一、该方法中必须为需要清除浮动元素的伪对象中设置 height:0,否则该元素会比实际高出若干像素;

   #parent:after{

  content:".";

  height:0;

  visibility:hidden;

  display:block;

  clear:both;

 }

  3.父元素添加overflow:hidden,触发BFC(块级上下文)机制,实现清除效果
  

```html

```html
    .fahter{
        width: 400px;
        border: 1px solid deeppink;
        overflow: hidden;
    }

  4.使用before和after双伪元素清除浮动
  

```html

```html
     .clearfix:after,.clearfix:before{
        content: "";
        display: table;
    }
    .clearfix:after{
        clear: both;
    }
    .clearfix{
        *zoom: 1;
    }
 
 <div class="fahter clearfix">
        <div class="big">big</div>
        <div class="small">small</div>
    </div>
    <div class="footer"></div>

Guess you like

Origin blog.csdn.net/weixin_49549509/article/details/107775442