解决子元素设置margin-top使父元素也跟着向下移动的问题

2 篇文章 0 订阅
文章介绍了CSS布局中常见的外边距塌陷问题,当子元素设置margin-top时,可能会引起父元素位置的变动。文章详细解释了这个问题的原理,并提供了七种解决方案,包括设置父元素的padding-top、border、overflow:hidden,以及对元素进行浮动和绝对定位等方法。
摘要由CSDN通过智能技术生成

先看代码:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>解决子元素设置margin-top使父元素也跟着向下移动的问题</title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}

			html,
			body {
				width: 100%;
				height: 100%;
			}

			.parent {
				background-color: skyblue;
				width: 100%;
				height: 100%;
			}

			.child {
				width: 50%;
				height: 50%;
				margin-top: 50px;
				background-color: pink;
			}
		</style>
	</head>
	<body>
		<div class="parent">
			<div class="child">
				这是子元素的内容
			</div>
		</div>
	</body>
</html>

以为的运行效果:

https://img-blog.csdnimg.cn/fc54a9eb06254d079b99dec22e201f18.png

实际上的运行效果:

子元素设置margin-top,父元素也跟着下移,造成外边距塌陷。

 原理:

        一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其内部文档流中的第一个子元素的上边距重叠。

解决办法:

1、给父元素设置padding-top

.parent {
	background-color: skyblue;
	width: 100%;
	height: 100%;
	box-sizing: border-box;
    padding-top: 1px;
}

2、为父元素设置border

.parent {
	background-color: skyblue;
	width: 100%;
	height: 100%;
	box-sizing: border-box;
	border: 1px solid transparent;
}

3、为父元素设置overflow: hidden;(推荐使用这种)

.parent {
	background-color: skyblue;
	width: 100%;
	height: 100%;
	overflow: hidden;
}

 4、为父元素设置浮动

.parent {
	background-color: skyblue;
	width: 100%;
	height: 100%;
	float: left;
}

5、为子元素设置浮动

.child {
	width: 50%;
	height: 50%;
	margin-top: 50px;
	background-color: pink;
	float: left;
}

6、为父元素设置绝对定位

.parent {
	background-color: skyblue;
	width: 100%;
	height: 100%;
	position: absolute;
}

7、为子元素设置绝对定位

.child {
	width: 50%;
	height: 50%;
	margin-top: 50px;
	background-color: pink;
	position: absolute;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值