盒子模型的塌陷

外边距塌陷

产生原因

  • 相邻块元素垂直外边距合并
    • 兄弟块元素,同时设置不同的 margin-top 值,两个的 margin-top 最后展示的都是最大的 margin-top 的效果。
  • html
<div class="brother1"></div>
<div class="brother2"></div>
  • style
.brother1{
    display: inline-block;
    width: 200px;
    height: 200px;
    background-color: goldenrod;
    margin-top: 50px;
}
.brother2{
    display: inline-block;
    width: 200px;
    height: 200px;
    background-color: hotpink;
    margin-top: 100px;
}
  • 效果

解决办法

  • 只给第一个元素设置 margin

外边距合并

产生原因

  • 嵌套块元素垂直外边距的合并
  • html
<div class="parent">
    <div class="child"></div>
</div>
  • css
.parent{
    width: 200px;
    height: 200px;
    background-color: goldenrod;
}
.child{
    width: 150px;
    height: 150px;
    background-color: hotpink;
    margin-top: 100px;
}
  • 效果

解决办法

  • 给父元素添加 boder-top
.parent {
    width: 200px;
    height: 200px;
    background-color: goldenrod;
    border-top: 4px solid #000000; /* 增加boder-top */
}

  • 给父元素添加 padding-top
.parent{
    width: 200px;
    height: 200px;
    background-color: goldenrod;
    padding-top: 10px;
}

  • 给父元素添加 overflow:hidden
    • 可能会导致超出的子元素被隐藏
.parent{
    width: 200px;
    height: 200px;
    background-color: goldenrod;
    overflow: hidden;
}

  • 给父元素添加 position:absolute;
  • 给父元素添加 display:inline-block;
posted @ 2020-08-04 00:32  _Sleeping  阅读(211)  评论(0)    收藏  举报