In-depth understanding of the usage of css's clearfix (must read article)

If there is a DIV as the outer container, if the inner DIV is set to float style, the outer container DIV cannot be opened because there is no clear inside. Look at the following example:
Div layout is as follows:

The Css code is as follows:

.out{border:1px solid #F00; width:500px;}   
.inner1{width:200px; height:200px; float:left; border:1px solid #00F;}   
.inner2{width:200px; height:200px; float:left; border:1px solid #0F0;}   
IE and FF show the following picture:

Traditional people's solution:

However, it is a bit wrong to add a DIV so much. One is that there is an extra meaningless DIV, and the other is that when using dojo to do Drag & Drop, because this DIV is a byte point of the container DIV, if this node is moved, it will cause a bug in the layout: if you want The DIV of the displayed blue box is moved after this DIV, because of clear:both, it will be forced to display in a new line. Therefore, it is best to use the following clearfix method. Add the clearfix style to the outer div.

clearfix is ​​defined as follows:

.clearfix:after{visibility:hidden;display:block;font-size:0;content: " ";clear:both;height:0;}   
.clearfix{*zoom:1;}   
 

After such modification, the display will be normal.

That piece of code is used to clear the float.

The following code can be explained like this:

.clearfix:after {       <----在类名为“clearfix”的元素内最后面加入内容;   
    content: ".";     <----内容为“.”就是一个英文的句号而已。也可以不写。   
    display: block;   <----加入的这个元素转换为块级元素。   
    clear: both;     <----清除左右两边浮动。   
    visibility: hidden;      <----可见度设为隐藏。注意它和display:none;是有区别的。仍然占据空间,只是看不到而已;   
    height: 0;     <----高度为0;   
    font-size:0;    <----字体大小为0;   
}  
 

The entire code is equivalent to an empty div with a width of 0 after the floating element, and then set it to clear: both to achieve the effect of clearing the float. (The principle of this css is to use the after pseudo-object, it will add the content in content at the end of the element to which clearfix is ​​applied, which is a ".", and set it as a block-level element (display="block"); height Set to 0, clear="both", and then hide its content (visibility="hidden"). This will open up this block-level element.)

The reason for using it is because you don't have to write a lot of meaningless empty tags in the html file, and you can clear the float.

.clearfix {*zoom:1;} <----This is for IE6, because IE6 does not support the :after pseudo-class, this magical zoom:1 allows IE6 elements to be cleared and floated to wrap internal elements. You don’t need to go into details about the specific meaning. I heard that Microsoft's engineers can't explain it clearly. Height: 1% has the same effect.

Original: https://www.jb51.net/css/490829.html

Guess you like

Origin blog.csdn.net/cherry_vicent/article/details/113245788