The issue you are facing is called collapsing margins.
Parent and first/last child
If there is no border, padding, inline content, or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
[source MDN emphasis mine]
If you want to prevent the collapsing margins on the element without the border, you can see other ways here : How to disable margin-collapsing?.
- float the parent
- change the parent display property to inline-block or
position:absolute;
- set the overflow of the parent to
hidden
- ...
Example with overflow:hidden;
:
.box {
background: #0F3;
border: 1px solid #000;
}
.box-border {
background: #0F3;
overflow:hidden;
}
.text {
margin: 40px;
}
<div class="box">
<div class="text">Content</div>
</div>
<div class="box-border">
<div class="text">Content</div>
</div>