1

According to Mozilla docs:
https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model#margin
a negative margin should works fine.

But example provided by Mozilla has border set on .container element.
Turns out that negative margin works only if border or padding is set on the container element.

If a container doesn't have border or padding set, then the negative margin on the child element doesn't work.

Is it a bug or a feature?
It works quite counterintuitively.

I can't find any rational explanation behind this behavior in the spec
https://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#mpb-examples

I reproduced this behavior in all major browsers: Chrome, Firefox, Safari, and Edge.

<div class="container">
  <div class="box"></div>
</div>
.container {
  background-color: blue;
  height: 300px;
  width: 500px;
  margin: 200px auto;

/* border or padding is required for negative margin to work */
/* border: 1px solid transparent; */
   padding: 1px;
}

.box {
  background-color: red;
  height: 200px;
  width: 400px;

  margin: -100px auto 0 auto;
}

enter image description here

.container {
  background-color: blue;
  height: 300px;
  width: 500px;
  margin: 200px auto;

/* border or padding is required for negative margin to work */
/* border: 1px solid transparent; */
/* padding: 1px; */
}

.box {
  background-color: red;
  height: 200px;
  width: 400px;

  margin: -100px auto 0 auto;
}

enter image description here

Codepen: https://codepen.io/adrianbienias/pen/MWJNYyw?editors=1100

Adrian Bienias
  • 829
  • 10
  • 16
  • 1
    the duplicate deal with positive margin but the same also apply to negative. TL;DR: your are facing margin-collapsing – Temani Afif May 02 '21 at 11:57
  • 1
    The "problem" disappears when setting conainer's border because margin collapsing happens only with elements without borders. – user14967413 May 02 '21 at 12:19

0 Answers0