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;
}
.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;
}
Codepen: https://codepen.io/adrianbienias/pen/MWJNYyw?editors=1100