穿透问题描述:
外边大盒子不设置padding-top或者border-top,只给小盒子设置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值穿透问题</title>
<style>
.parent{
width: 300px;
height: 300px;
background-color: rgb(175, 28, 243);
}
.child{
width: 100px;
height: 100px;
margin: 20px auto;
background-color: paleturquoise;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
浏览器效果如下:
![](https://img-blog.csdnimg.cn/img_convert/0f3e8b433f2e4e7dabfe78eece864ca7.png)
如上图,只给大盒子设置了宽高,然后给小盒子设置宽高在设置margin值时,下间距和左右间距不影响,但是上间距导致大盒子随着一起掉下来了。
解决方法:
给大盒子添加overflow: hidden;
给大盒子设置上边框border-top: 1px solid transparent;
代码实例:
<!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值穿透问题</title>
<style>
/*
描述:
外边大盒子不设置padding-top或者border-top,只给小盒子设置margin-top,外边大盒子会随着小盒子下掉
*/
.parent{
width: 300px;
height: 300px;
/*
第一种方法给大盒子添加:
overflow: hidden;
*/
/*
第二种方法给大盒子添加:
border-top: 1px solid transparent;
*/
border-top: 1px solid transparent;
background-color: rgb(175, 28, 243);
}
.child{
width: 100px;
height: 100px;
margin: 20px auto;
background-color: paleturquoise;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
浏览器效果:
![](https://img-blog.csdnimg.cn/img_convert/152ce7294cde67b31174bd88bc38ff12.png)
合并问题描述:
上下两个盒子box1和box2,给上box1设置了margin-bottom,给box2设置了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值穿透问题</title>
<style>
/*
描述:
外边大盒子不设置padding-top或者border-top,只给小盒子设置margin-top,外边大盒子会随着小盒子下掉
*/
.parent{
width: 300px;
height: 300px;
margin-bottom: 10px;
background-color: rgb(175, 28, 243);
}
.one{
width: 300px;
height: 300px;
margin-top: 20px;
background-color: powderblue;
}
</style>
</head>
<body>
<div class="parent"></div>
<div class="one"></div>
</body>
</html>
浏览器效果:
![](https://img-blog.csdnimg.cn/img_convert/963a101e8252208458933ee1c6509a0d.png)