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

先看代码:

<!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>

以为的运行效果:

实际上的运行效果:

 

子元素设置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;
}

猜你喜欢

转载自blog.csdn.net/qq_39998026/article/details/131633965