CSS显示块属性边距问题

时间:2016-12-27 00:37:41

标签: html css html5 css3 margin

有时我在div上使用margin(display:block)并且没有正常工作,但是对于内联块工作,我怀疑是什么原因?这种情况下的保证金是否应该以同样的方式运作?

我知道我可以使用.box margin-top,.box + box margin-top等...但这不是问题。



.box {
  border: 1px solid #500;
}
.block-div-margin {
  margin: 10px 0;
  display: block;
  /*default div state*/
}
.inline-block-div-margin {
  display: inline-block;
  margin: 10px 0;
}
.my-div {
  padding: 20px;
  background: #EAEAEA;
  border-bottom: 1px solid #999;
}
.my-other-div {
  background: #D3E1E1;
  padding: 0 20px 20px 20px;
}
.my-other-div-content {
  margin-top: 20px;
}
.my-div-inline-block {
  display: inline-block;
  width: 100%;
  box-sizing: border-box;
}

<h2>Example 1</h2>
<h3>block-div-margin</h3>
<div class="container">
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas, nobis.</div>
  <div class="block-div-margin"></div>
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque, delectus!</div>
  <div class="block-div-margin"></div>
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur, quasi.</div>
  <div class="block-div-margin"></div>
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro, id!</div>
</div>

<h3>inline-block-div-margin</h3>
<div class="container">
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas, nobis.</div>
  <div class="inline-block-div-margin"></div>
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque, delectus!</div>
  <div class="inline-block-div-margin"></div>
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur, quasi.</div>
  <div class="inline-block-div-margin"></div>
  <div class="box">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro, id!</div>
</div>

<h2>Example 2</h2>
<h3>This is more common issue that I see ever</h3>
<div class="my-div">
  This is my-div content
</div>
<div class="my-other-div">
  <div class="my-other-div-content">
    This is my-other-div-content
  </div>
</div>

<h3>With div inline-block</h3>
<div class="my-div">
  This is my-div content
</div>
<div class="my-other-div my-div-inline-block">
  <div class="my-other-div-content">
    This is my-other-div-content
  </div>
</div>
&#13;
&#13;
&#13;

即使将元素放在另一个元素中,当添加边距时,就好像我在父元素中添加了边距而不是在子元素中。

enter image description here

1 个答案:

答案 0 :(得分:3)

它称为折叠边距,并且不会在内联块上发生。

8.3.1 Collapsing margins

  

内联块方框的边距不会崩溃(即使是流入的子节点也不会崩溃)。

关注this post以了解更多避免此问题的方法。