小编好多次打代码遇到了设置外边距,整个大块向下移动的问题,这也就是嵌套块元素外边距塌陷问题。 今天总结了一些方法,我们一起来学习一下吧,今天全是干货哈!塌陷问题描述:父元素400400,子元素200200,父元素设置margin-top:50px;子元素设置margin-top:100px;则父元素向下移动150px。嵌套块元素垂直外边距塌陷问题,解决方案:1.给父元素添加边框,可以设置1像素边框,把颜色改为透明色。2.给父元素添加1像素内边距。3.给父元素添加overflow:hidden。4.浮动。5.固定,定位(绝对定位)。
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<style>
.one{
width: 400px;
height: 400px;
background-color: blue;
margin-top: 50px;
/* 方案1:边框 */
/* border: 1px solid transparent; */
/* 1像素实心透明 */
/* 方案2:内边距 */
/* padding: 1px; */
/* 方案3:overflow:hidden; */
/* overflow: hidden;*/
/* 方案4:浮动 */
/* float: left; */
/* 方案5:绝对定位 */
position: absolute;
}
.two{
width: 200px;
height: 200px;
background-color: green;
margin-top: 100px;
}
</style>
</head>
<body>
<h2>嵌套块元素外边距塌陷问题解决方法</h2>
<h3>解决方案:1.设置边框2.添加内边距3.overflow:hidden;4.浮动5.绝对定位</h3>
<div class="one">
<div class="two"></div>
</div>
</body>
</html>