清除浮动

清除浮动

浮动副作用

当元素设置float浮动后,该元素就会脱离文档流并向左/向右浮动.

  1. 浮动元素会造成父元素高度塌陷
  2. 后续元素会受到影响

<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
.container{
	border:1px solid red;
}
.box{
	width:100px;
	height:100px;
	background-color:#fff176;
	float:right;
	margin:0 5px;
}

清除浮动

当父元素出现塌陷的时候,对布局是不利的,所以我们必须清除副作用解决方案有很多种

  1. 父元素设置高度
  2. 受影响的元素增加clear属性
  3. overflow清除浮动
  4. 伪对象方式
父元素设置高度

如果父元素高度塌陷,可以给父元素设置高度,撑开元素本身大小

overflow清除浮动

如果有父级塌陷,并且同级元素也收到了影响,可以使用overflow清除浮动这种情况下,父布局不能设置高度

父级标签的样式里面加:overflow:hidden;clear:both

<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="nav"></div>
.container{
	width:350px;
	border:1px solid red;
	overflow:hidden;
	clear:both;
}
.box{
	width:100px;
	height:100px;
	background-color:#fff176;
	float:left;
	margin:0 5px;
}
.nav{
	width:100px;
	height:100px;
	background-color:red;
}

伪对象方式

如果有父级塌陷,并且同级元素也收到了影响,还可以使用伪对象方式处理为父标签添加伪类after,设置空的内容,并且使用clear:both;

这种情况下,父布局不能设置高度

<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="nav"></div>
.container{
	width:350px;
	border:1px solid red;
	}
.container::after{
	content:"";
	display:block;
	clear:both;
}
.box{
	width:100px;
	height:100px;
	background-color:#fff176;
	float:left;
	margin:0 5px;
}
.nav{
	width:100px;
	height:100px;
	background-color:red;
}
posted @ 2023-03-23 21:51  土著古  阅读(23)  评论(0)    收藏  举报