How to clear floats?

How to clear float

1. Set the height of the parent element (generally not recommended)
2. Clear syntax:

Selector {clear: attribute value} clear: clear

Attribute value description
left Do not allow floating elements on the left (clear the effect of floating on the left)
right Do not allow floating elements on the right (clear the effect of floating on the right)
both At the same time remove the impact of floating on the left and right sides

ps: In actual work, we almost only use clear: both

3. Extra labeling method (partition wall method)

是在w3c推荐的做法是通过在浮动元素末尾添加一个空的标签,例如:<div style="clear:both"></div>或者其他标签(br)即可。
  • Advantages: easy to understand, easy to write

  • Disadvantages: add many meaningless tags, poor structure

Fourth, the parent adds the overflow attribute method

可以给父级添加:overflow为hidden|auto|scroll  都可以实现
  • Advantages: simple code
  • Disadvantages: When the content is large, it is easy to cause the content to be hidden without automatic line wrapping, and it is impossible to display the elements that need to overflow

Five, use the after pseudo element to clear the float

  :after方式为空元素额外标签法的升级版,好处是不用单独加标签了

Instructions:

.clearfix:after{
	content:"";
	display:block;
	height:0;
	clear:both;
	visibility:hidden;
}
.clearfix{
	*zoom:1;/* IE6、7 专有 */
}
  • Advantages: In line with the closed floating idea, the structure is semantically correct
  • Disadvantages: Since IE6-7 does not support :after, use zoom:1 to trigger hasLayout.
  • Representative websites: Baidu, Taobao, Netease, etc.

Six, use double pseudo elements to clear floats

Instructions:

.clearfix:after,:clearfix:before{
	content:"";
	display:table;
}
.clearfix:after{
	clear:both;
}
.clearfix{
	*zoom:1;/* IE6、7 专有 */
}
  • Advantages: the code is more concise
  • Disadvantages: Since IE6-7 does not support :after, use zoom:1 to trigger hasLayout.
  • Representative websites: Xiaomi, Tencent, etc.

Clear floating summary:

  1. Parent has no height
  2. Child box floating
  3. Affect the following layout,
Ways to clear floats advantage Disadvantage
Extra label method (partition wall method) Easy to understand and easy to write Add many meaningless tags
父级overflow:hidden; Simple to write Overflow hiding
Parent after pseudo element The structure is semantically correct Because IE6-7 does not support: after, compatibility issues
Parent double pseudo element The structure is semantically correct Because IE6-7 does not support: after, compatibility issues

Guess you like

Origin blog.csdn.net/December_shi/article/details/108620575