清除浮动的四种方法

207 阅读2分钟

浮动元素:浮动元素会脱离普通文档流向左右浮动,直到碰见其父元素或其他的浮动元素。

浮动元素可实现内联排列,同时也会导致父元素的高度坍塌。

清除浮动的方法:

1、overflow: hidden|auto

浮动后的元素会脱离普通文档流,父元素高度无法撑开,通过给父元素设置overflow属性,触发隐藏属性BFC。

给浮动元素的父元素设置高度也可解决浮动带来的高度坍塌问题。

优点:代码简洁;
缺点:父级元素内容增多时不会自动换行,会隐藏;

例子:

html:
<div id="parent">
	<div id="child1"></div>
	<div id="child2"></div>	
	<div id="child3"></div>
</div>
css:
#parent{
	width: 500px;
	background: black;
	overflow: hidden;
}
#child1, #child2, #child3{
	width: 100px;
	height: 100px;
	margin: 20px;
	float:left;
}
#child1 {
	background: pink;
}
#child2 {
	background: orange;
}
#child3 {
	background: lightblue;
}

2、空白标签法+clear

优点:书写简单;
缺点:添加无意义标签,结构化较差;

例子:

html:
<div id="parent">
    <div id="child1"></div>
    <div class="clear"></div>
    <div id="child2"></div>
    <div class="clear"></div>
    <div id="child3"></div>
    <div class="clear"></div>
</div>
css:
#parent{
	width: 500px;
	background: black;
}
.clear{
    clear:both;
}
#child{
	width: 100px;
	height: 100px;
    background: pink;
	margin: 20px;
	float:left;
}

3、clear:left|right|both+伪元素

clear属性规定元素的哪一侧不允许其他浮动元素,clear属性只会对自身起作用,而不会影响其他元素。

优点:空白标签法的升级,无须单独加标签,结构语义化;
缺点:IE6、7不支持,需要给父元素设置zoom:1;

例子:

html:
<div id="parent">
	<div id="child1"></div>
	<div id="child2"></div>
	<div id="child3"></div>
</div>
css:
#parent{
	width: 500px;
	background: black;
}
#parent:after{
	content: "";
	display: block;
	clear: both;
}
#child1, #child2, #child3{
	width: 100px;
	height: 100px;
	margin: 20px;
	float:left;
}
#child1 {
	background: pink;
}
#child2 {
	background: orange;
}
#child3 {
	background: lightblue;
}

4、双伪元素清除浮动

例子:

html:
<div id="parent">
	<div id="child"></div>
</div>
css:
#parent{
	width: 500px;
	background: black;
}
#parent:before, #parent:after{
	content: ".";
	display: table;
}
#parent:after{
	clear: both;
}
#child{
	width: 100px;
	height: 100px;
	background:white;
	margin: 20px;
	float:left;
}