What are the ways to clear floats?

Reference: CSS floating and 5 ways to clear floating

1. Why clear floats?

  1. Standard flow: The boxes will each occupy the entire row. If the child box is a standard stream, although the parent box has no height, it will stretch the height of the parent box.
  2. Floating: The box floats and will not occupy its original position. If the parent box has no defined height, the parent box will not be opened, and the height of the parent box is 0. Note : (Floating allows multiple block-level elements to be displayed in one line, and there is no gap between the blocks, but pay attention to clear the float for the parent box, otherwise the parent box will not be stretched).

Therefore, clearing the float is mainly to solve the problem that the internal height of the parent element is 0 caused by the child float .

2. How to clear float

  1. The parent div defines a pseudo-class:after and is zoomrecommended
.clearfix:after{
    content:"";  /*设置内容为空*/
    height:0;  /*高度为0*/
    line-height:0;  /*行高为0*/
    display:block;  /*将文本转为块级元素*/
    visibility:hidden;  /*将元素隐藏*/
    clear:both;  /*清除浮动*/
}
.clearfix{
    zoom:1;  /*为了兼容IE*/
}

Advantages: browser support is good, not prone to strange problems.
Disadvantages: two sentences of code must be combined to make mainstream browsers support
2. Add a blank div tag at the end and use itclear:both mainly

//对添加的元素使用 clear:both
.clear{clear:both;}
<div class="box">
    <div class="red" style="float:left;">1</div>
    <div class="sienna" style="float:left;">2</div>
    <div class="blue" style="float:left;">3</div>
    //添加一个新元素
    <div class="clear"></div>
</div>

Advantages: simple, less code, good browser support, not prone to strange problems.
Disadvantages: if there are many floating layouts on the page, a lot of empty divs must be added

  1. Parent div definition : overflow:hidden
    advantages: simple, less code, good browser support.
    Disadvantages: width or zoom:1 must be defined, and cannot be used with position

  2. The parent div defines the height.
    Advantages: simple, less code.
    Disadvantages: only suitable for fixed-height layouts, and accurate heights must be given

  3. Parent div definitionoverflow:auto
    Advantages: simple, less code, good browser support
    Disadvantages: scroll bars will appear when the internal width and height exceed the parent div

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108452096