CSS - 外边距合并

1. 外边距合并

当上下相邻的两个块元素相遇时,如果上面的元素有下外边距margin-bottom,下面的元素有上外边距margin-top,则他们之间的垂直间距不是margin-bottom与margin-top之和,而是两者中的较大者。这种现象被称为相邻块元素垂直外边距的合并(也称外边距塌陷)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    div {
        width: 300px;
        height: 200px;
        background-color: purple;
    }
    .xiongda {
        margin-bottom: 100px;
    }
    .xionger {
        background-color: pink;
        margin-top: 150px;  /*最终两个盒子的距离是  最大的那个为准  150*/
    }
    </style>
</head>
<body>
    <div class="xiongda">1</div>
    <div class="xionger">2</div>
</body>
</html>

解决方案:避免。

2. 嵌套块元素垂直外边距的合并

对于两个嵌套关系的块元素,如果父元素没有上内边距及边框,则父元素的上外边距会与子元素的上外边距发生合并,合并后的外边距为两者中的较大者,即使父元素的上外边距为0,也会发生合并。

解决方案:

  1. 可以为父元素定义1像素的上边框或上内边距。
  2. 可以为父元素添加overflow:hidden。

猜你喜欢

转载自www.cnblogs.com/allen2333/p/9011705.html
今日推荐