子元素设置margin-top为什么会作用在父元素上?

图片描述

如图,为什么我给p标签元素设置的margin-top会作用在div上面?

<div class="test">
    <p class="para">this is a para</p>
</div>
* {
    padding: 0;
    margin: 0;
}
.test {
    position: relative;
    height: 400px;
    width: 1000px;
    margin: 0 auto;
    margin-top: 0;
    margin-bottom: 0;
    background-color: #DCF1B8;
}
.para {
    width: 20%;
    margin-left: auto;
    margin-right: auto;
    background-color: #734E4E;
    height: 50%;
    margin-top: 100px;
    margin-bottom: 100px;
}
阅读 3.2k
3 个回答

因此推荐尽量优先使用padding来控制间距

来看css2.1盒模型中规定的内容:In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin. 所有毗邻的两个或更多盒元素的margin将会合并为一个margin共享之。毗邻的定义为:同级或者嵌套的盒元素,并且它们之间没有非空内容、Padding或Border分隔。

解决办法:

  1. 父级或子元素使用浮动或者绝对定位absolute

浮动或绝对定位不参与margin的折叠

  1. 父级overflow:hidden;
  2. 父级设置padding(破坏非空白的折叠条件)
  3. 父级设置border
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题