何为margin合并塌陷

158 阅读1分钟

一、何为margin合并塌陷

首先,若设置两个div盒子,一个设置margin-top:100px,一个设置为margin-bottom:150px

正常来说,应当是两个div盒子相距250px,但实际应当是相距150px,因为这就是margin合并问题,且会显示margin较大的那一个

解决方法便是,推荐直接计算需要的间距,加在其中一个div上

二、何为塌陷问题

注意:合并塌陷存在于父子关系的div上

eg:我给父元素设置为margin-top:100px

子元素设置margin-top:100px

会发现子元素贴着父元素的顶部,没有出现margin-top,这就是塌陷问题:即父元素像是塌陷了一样直接让子元素浮上去了

解决方法:

.加一个透明的边框

即:加一个border: 1px solid transparent;

image-20220104183808400

<style>
    
    .father{
        width: 500px;
        height: 500px;
        background-color: rgb(15, 213, 240);
        margin-top: 100px;
        border: 1px solid transparent;
    }
    .son{
        width: 300px;
        height: 300px;
        background-color: rgb(14, 71, 226);
        margin-top: 50px;
    }
</style>
<body>
    <div class="father">
        <div class="son">
​
        </div>
    </div>
</body>

2.给父元素加一个内边距

即:padding:1px;

image-20220104183808400

<style>
    
    .father{
        width: 500px;
        height: 500px;
        background-color: rgb(15, 213, 240);
        margin-top: 100px;
        padding: 1px;
    }
    .son{
        width: 300px;
        height: 300px;
        background-color: rgb(14, 71, 226);
        margin-top: 50px;
    }
</style>
<body>
    <div class="father">
        <div class="son">
​
        </div>
    </div>
</body>

3.给父元素加一个overflow:hidden;

4.其他