0

I have box with a child div. The child has a margin. If I set a border on the parent (div.box) the height of the element changes as shown in the following image. Where is the trick?

Border on parent and margin on child

.box {
  background: #0F3;
  border: 1px solid #000;
}
.box-border {
  background: #0F3;
}
.text {
  margin: 40px;
}
<div class="box">
  <div class="text">Content</div>
</div>

<div class="box-border">
  <div class="text">Content</div>
</div>
web-tiki
  • 99,765
  • 32
  • 217
  • 249
Marko
  • 25
  • 1
  • what do you mean wierd view? May be this will help you :) http://stackoverflow.com/questions/35337043/when-i-try-to-shift-the-image-upwards-using-negative-margin-the-whole-container/35337103#35337103 – Bhojendra Rauniyar Feb 12 '16 at 09:06
  • maybe you have to see this http://stackoverflow.com/questions/1762539/margin-on-child-element-moves-parent-element – Az.Youness Feb 12 '16 at 09:12
  • did you see printscreen?...once box have border... – Marko Feb 12 '16 at 09:17

1 Answers1

1

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>
Community
  • 1
  • 1
web-tiki
  • 99,765
  • 32
  • 217
  • 249