css外边距margin的塌陷问题
子级元素的外边距margin同时也会影响到父级元素,这就是css外边距的塌陷问题。
举个例子:
<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
text-decoration: none;
}
div {
background-color: pink;
height: 100px;
width: 100px;
}
div.father {
background-color: pink;
}
div.child {
/* margin-top: 80px; */
background-color: orange;
height: 50px;
width: 50px;
}
</style>
</head>
<body>
<div class="father">
<div class="child">child</div>
</div>
</body>
</html>
显示的结果为:
当在子级元素设置外边距时,会同时影响到父级元素:
<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
text-decoration: none;
}
div {
background-color: pink;
height: 100px;
width: 100px;
}
div.father {
background-color: pink;
}
div.child {
margin-top: 80px;
background-color: orange;
height: 50px;
width: 50px;
}
</style>
</head>
<body>
<div class="father">
<div class="child">child</div>
</div>
</body>
</html>

解决办法:
- 父级元素控制内边距即可。
- 父级元素添加overflow字段取值为hidden
<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
text-decoration: none;
}
div {
background-color: pink;
height: 100px;
width: 100px;
}
div.father {
padding-top: 25px;
background-color: pink;
}
div.child {
/* margin-top: 80px; */
background-color: orange;
height: 50px;
width: 50px;
}
</style>
</head>
<body>
<div class="father">
<div class="child">child</div>
</div>
</body>
</html>


浙公网安备 33010602011771号