子元素 margin-top/上外边距 影响父元素位置且不相对父元素定位

子元素通过 marign-top 或 margin 设置上外边距之后,在实际页面中却发现,父元素的上外边距受到了影响,且子元素的上外边距也并没有相对父元素进行定位。


举例说明:

<!-- html中内容 -->
<div class="father">
  <div class="children"></div>
</div>
/* style中内容 */
* {
  margin: 0px;
}
.father {
  margin-top: 10px;
  width: 300px;
  height: 200px;
  background-color: #FFDADF;
}

.children {
  margin-top: 30px;
  width: 100px;
  height: 100px;
  background-color: #FF7485;
}

以下是想要的效果:

预期效果

这是实际的效果:

实际效果

可以发现,实际页面效果跟我们写代码时的预期不一样。

其实,这是 margin 塌陷的几种情况之一,解决方法有以下四种:

一、为父元素添加 overflow

为父元素添加样式:overflow: hidden/auto/scroll


.father {
  margin-top: 10px;
  width: 300px;
  height: 200px;
  background-color: #FFDADF;
  overflow: hidden;
}

二、使父元素 positon 不是 static 或 relative

为父元素添加样式:position: absolute/fixed/sticky 等(除 static relative 皆可)

.father {
  margin-top: 10px;
  width: 300px;
  height: 200px;
  background-color: #FFDADF;
  position: absolute;
}
三、使父元素 float 不为 none

为父元素添加样式:float: left/right 等(除 none 皆可)

.father {
  margin-top: 10px;
  width: 300px;
  height: 200px;
  background-color: #FFDADF;
  float: left;
}
四、使父元素 display 为 table-cli 或 inline

为父元素添加样式:display: table-cli/inline

.father {
  margin-top: 10px;
  width: 300px;
  height: 200px;
  background-color: #FFDADF;
  display: table-cli;
}

关于 margin 塌陷的详解文章:

margin塌陷和margin合并问题及解决方案

经典CSS缺陷--margin塌陷问题和margin合并问题

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。