css清除浮动产生影响的三种方式

清除浮动:

清除浮动不是不会浮动,只是消除浮动产生的不利影响

当父盒子没有定义高度,嵌套在父盒子内部的子盒子发生浮动后,父盒子下边的元素位置发生错误,即父盒子中的子元素脱标

1、额外标签法

<div class="con fixclear" style="overflow:hidden"><!-- 我是父元素 -->
	<div class="con-left"></div><!-- 浮动元素 -->
	<div class="con-right"></div><!-- 浮动元素 -->
	<!-- 额外标签清除浮动 -->
	<div class="clear" style="clear:both"></div><!-- 添加的就是我 -->
</div>

clear: left | right | both; 

在最后一个浮动元素后面添加标签 

2、给父元素使用overflow:hidden (bfc)

<!-- 给父元素使用overflow:hidden (bfc) -->
<div class="con fixclear" style="overflow:hidden"><!-- 我是父元素 -->
	<div class="con-left"></div><!-- 浮动元素 -->
	<div class="con-right"></div><!-- 浮动元素 -->
</div>

如果有内容超出了盒子的话,就不能使用它,因为超出的部分被隐藏掉了

3、伪元素清除浮动(推荐使用)

/* 伪元素清除浮动 */
.fixclear:after{
	content: ".";
	display: block;
	visibility: hidden;
	line-height: 0;
	clear: both;
}
/* 兼容ie浏览器 */
    .fixclear{
	zoom: 1;
}

给浮动元素的父元素使用.clearfix即可

最后贴一下代码: 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.top{
			width: 500px;
			height: 100px;
			background: yellow;
		}
		.con{
			width: 500px;
			/* height: 300px; */
		}
		.con .con-left{
			width: 250px;
			height: 300px;
			float: left;
			background: red;
		}
		.con .con-right{
			width: 250px;
			height: 300px;
			background: green;
			float: right;
		}
		.bottom{
			width: 500px;
			height: 100px;
			background: black;
		}
		/* 伪元素清除浮动 */
		.fixclear:after{
			content: ".";
			display: block;
			visibility: hidden;
			line-height: 0;
			clear: both;
		}
		/* 兼容ie浏览器 */
		.fixclear{
			zoom: 1;
		}
	</style>
</head>
<body>
	<div class="top"></div>
	<!-- 给父元素使用overflow:hidden (bfc) -->
	<div class="con fixclear" style="overflow:hidden"><!-- 我是父元素 -->
		<div class="con-left"></div><!-- 浮动元素 -->
		<div class="con-right"></div><!-- 浮动元素 -->
		<!-- 额外标签清除浮动 -->
		<div class="clear" style="clear:both"></div><!-- 添加的就是我 -->
	</div>
	<div class="bottom"></div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_42634193/article/details/84034268