CSS里设置子元素浮动导致父元素高度塌陷的解决办法(清除浮动)

一、未设置子元素浮动的效果。

<!DOCTYPE html>
<html lang="en">

<head>
  <style>
	.box{
		background-color:red;
		width:100%;
	}
	.box1{
		width:50%;
		height:200px;
		background-color:blue;
		text-align:center;
		line-height:200px;
		font-size:50px;
	}
	.box2{
		width:50%;
		height:200px;
		background-color:#03A9F4;
		text-align:center;
		line-height:200px;
		font-size:50px;
	}
	
  
  </style>
</head>

<body>
<div class="box">
	<div class="box1">box1</div>
	<div class="box2">box2</div>

</div>
  
</body>

</html>

二、设置子元素浮动效果。

<!DOCTYPE html>
<html lang="en">

<head>
  <style>
	.box{
		background-color:red;
		width:100%;
	}
	.box1{
		width:50%;
		height:200px;
		background-color:blue;
		text-align:center;
		line-height:200px;
		font-size:50px;
	}
	.box2{
		width:50%;
		height:200px;
		background-color:#03A9F4;
		text-align:center;
		line-height:200px;
		font-size:50px;
	}
	.box>div{
		float:left;
	}
	
  
  </style>
</head>

<body>
<div class="box">
	<div class="box1">box1</div>
	<div class="box2">box2</div>

</div>
  
</body>

</html>

可以看到设置子元素浮动以后,box父元素高度塌陷了,没有高度了。

三、解决子元素浮动导致的父元素塌陷问题(清除浮动)。

1、给父元素box后面添加伪元素清除浮动,设置.box::after

<!DOCTYPE html>
<html lang="en">

<head>
  <style>
	.box{
		background-color:red;
		width:100%;
	}
	.box1{
		width:50%;
		height:200px;
		background-color:blue;
		text-align:center;
		line-height:200px;
		font-size:50px;
	}
	.box2{
		width:50%;
		height:200px;
		background-color:#03A9F4;
		text-align:center;
		line-height:200px;
		font-size:50px;
	}
	.box>div{
		float:left;
	}
	.box::after{
		content:"";
		display:block;
		clear:both;
	}
	
  
  </style>
</head>

<body>
<div class="box">
	<div class="box1">box1</div>
	<div class="box2">box2</div>

</div>
  
</body>

</html>

可以看到高度被子元素撑开了200px。

2、直接给box父元素添加overflow:auto;或者overflow:hidden属性

.box{
		background-color:red;
		width:100%;
		overflow:auto;
	}

父元素高度同样也可以被子元素撑开。

3、设置父元素box属性float: left,让父元素同样脱离文档流。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值