如何解决 margin“塌陷”?

277 阅读1分钟

如何解决 margin“塌陷”?

一、什么是“塌陷”?

塌陷现象是指:当两个盒子在垂直方向上设置margin属性值的时候,紧紧挨在一起,出现叠加现象

通常出现在兄弟关系的盒子和父子关系的盒子

<!-- 父子关系盒子塌陷例子 -->
<style>
    .box {
        width: 200px;
        height: 200px;
        background-color: skyblue;
    }
​
    .son {
        width: 100px;
        height: 100px;
        background-color: pink;
        margin-top: 100px;
    }
</style><body>
    <div class="box">
        <div class="son">
​
        </div>
    </div>
</body>

理想效果

理想.png

现实效果

塌陷现象.png

二、如何解决“塌陷”呢?

1、将父元素的高度设置一下

塌陷示例

关键代码:

height:200px;

示例

<style>
    .box {
        width: 200px;
        height:200px;
        background-color: skyblue;
​
    }
​
    .son {
        float: left;
        width: 100px;
        height: 200px;
        background-color: pink;
    }
</style><body>
    <div class="box">
        <div class="son"></div>
    </div>
</body>

塌陷样子

浮动塌陷.png

后来效果

效果.png

2、给父元素添加overflow: hidden;属性

关键代码:

overflow: hidden;

实例

<style>
    .box {
        width: 200px;
        background-color: skyblue;
        overflow: hidden;
    }
​
    .son {
        float: left;
        width: 100px;
        height: 200px;
        background-color: pink;
    }
</style><body>
    <div class="box">
        <div class="son"></div>
    </div>
</body>

3、在浮动元素下方添加空div,并给元素声明clear:both

关键代码:

<div style="height: 0;overflow: hidden;clear: both;"></div>

示例

<style>
    .box {
        width: 200px;
        background-color: skyblue;
    }
​
    .son {
        float: left;
        width: 100px;
        height: 200px;
        background-color: pink;
    }
</style>
​
<body>
    <div class="box">
        <div class="son"></div>
        <div style="height: 0;overflow: hidden;clear: both;"></div>
    </div>
</body>

4、清除浮动

关键代码:

.box::after {
        content: "";
        display: block;
        clear: both;
    }

示例

<style>
    .box {
        width: 200px;
        background-color: skyblue;
    }
​
    .son {
        float: left;
        width: 100px;
        height: 200px;
        background-color: pink;
    }
​
    .box::after {
        content: "";
        display: block;
        clear: both;
    }
</style><body>
    <div class="box">
        <div class="son"></div>
    </div>
</body>

5、给父元素添加浮动

关键代码:

float:left;

示例

<style>
    .box {
        width: 200px;
        background-color: skyblue;
        float: left;
    }
​
    .son {
        float: left;
        width: 100px;
        height: 200px;
        background-color: pink;
    }
</style><body>
    <div class="box">
        <div class="son"></div>
    </div>
</body>

6、给父元素添加border属性

关键代码:

border: 1px solid #000;

示例

<style>
    .box {
        width: 200px;
        height: 200px;
        background-color: skyblue;
        border: 1px solid #000;
    }
​
    .son {
        width: 100px;
        height: 100px;
        background-color: pink;
        margin-top: 100px;
​
    }
</style><body>
    <div class="box">
        <div class="son">
​
        </div>
    </div>
</body>