Sometimes I use margin on div (display: block) and doesn't work properly, but with inline-block works, my doubt is why? Should the margin in this case work in the same way?
I know that I can use .box margin-top, .box + box margin-top, etc... but this is not the question.
.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>
Even with the element inside another element, when adding margin, it is as if I have added the margin in the parent element and not in the child.
It's called collapsing margins, and that doesn't happen on inline blocks.
8.3.1 Collapsing margins
Follow this post for more ways to avoid that.