天天看點

常見的清除浮動的四種方法

方法一

在父元素的最後加一個空的div标簽,給新加的div标簽定義css屬性clear:both;

.father {
	width: 100%;
	border: 1px solid red;
}
.son {
	width: 100px;
	height: 100px;
	float: left;
}
.son1 {
	background-color: #ff0;
}
.son2 {
	background-color: #0ff;
}
.son3 {
	background-color: #f0f;
}
.clear {
	clear: both;
}

<div class="father">
	<div class="son1 son">1</div>
	<div class="son2 son">2</div>
	<div class="son3 son">3</div>
	<div class="clear"></div>
</div>
           

運作結果:

常見的清除浮動的四種方法

方法二

給包含浮動元素的父級元素定義僞元素::after,并将為元素的display定義為block類型

.father {
	width: 100%;
	border: 1px solid red;
}
father::after {
	content: "";
	display: block;
	clear: both;
}
           

方法三

給包含浮動元素的父級元素定義overflow:hidden;

.father {
	width: 100%;
	border: 1px solid red;
	overflow: hidden;
}
           

方法四

給包含浮動元素的父級元素定義高度

.father {
	width: 100%;
	height: 100px;
	border: 1px solid red;
}