«

CSS-盒子模型-外边距折叠现象-塌陷现象

时间:2023-2-16 21:50     作者:吾峰     分类: 前端开发


场景:互相嵌套的块级元素,子元素的 margin-top 会作用在父元素上

结果:导致父元素一起往下移动

解决方法:

  1. 给父元素设置border-top 或者 padding-top (分隔父子元素margin-top)
    2.给父元素设置overflow:hidden(推荐)
    3.转换成行内块元素
    4.设置浮动
<!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>
        .father {
            width: 300px;
            height: 300px;
            background-color: pink;
            overflow: hidden;
        }

        .son {
            width: 100px;
            height: 100px;
            background-color: skyblue;
            margin-top: 50px ;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son">son</div>
    </div>
</body>
</html>

标签: css


扫描二维码,在手机上阅读