css_margin塌陷问题解决方法

发布时间 2023-07-08 20:36:54作者: Espre-sso

css_margin塌陷问题

问题描述

<div class="father">
    <div class="child1"></div>
    <div class="child2"></div>
</div>

child1设置了margin-top时,margin-top会作用在father上

child2设置了margin——bottom时,margin-bottom会作用在father上

解决方法

  • 给father设置 overflow:hidden;
.father{
    overflow:hidden;
}

历史遗留问题,这样解决最好,因为不会影响father的大小,其他方式会影响father的大小,比如:

  • 给father设置不为0的padding(内边距)
  • 给father设置不为0的border(边框)