I had similar problem with margin collapse because of parent having position
set to relative. Here are list of commands you can use to disable margin collapsing.
Just try to assign any parent-fix*
class to div.container
element, or any class children-fix*
to div.margin
. Pick the one that fits your needs best.
When
div.absolute
with red background will be positioned at the very top of the page.div.absolute
will be positioned at the same Y coordinate as div.margin
html, body { margin: 0; padding: 0; }_x000D_
_x000D_
.container {_x000D_
width: 100%;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 50px;_x000D_
right: 50px;_x000D_
height: 100px;_x000D_
border: 5px solid #F00;_x000D_
background-color: rgba(255, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
.margin {_x000D_
width: 100%;_x000D_
height: 20px;_x000D_
background-color: #444;_x000D_
margin-top: 50px;_x000D_
color: #FFF;_x000D_
}_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
collapsing from within parent (.container) */_x000D_
.parent-fix1 { padding-top: 1px; }_x000D_
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}_x000D_
.parent-fix3 { overflow: auto;}_x000D_
.parent-fix4 { float: left;}_x000D_
.parent-fix5 { display: inline-block; }_x000D_
.parent-fix6 { position: absolute; }_x000D_
.parent-fix7 { display: flex; }_x000D_
.parent-fix8 { -webkit-margin-collapse: separate; }_x000D_
.parent-fix9:before { content: ' '; display: table; }_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
collapsing from within children (.margin) */_x000D_
.children-fix1 { float: left; }_x000D_
.children-fix2 { display: inline-block; }
_x000D_
<div class="container parent-fix1">_x000D_
<div class="margin children-fix">margin</div>_x000D_
<div class="absolute"></div>_x000D_
</div>
_x000D_
Here is jsFiddle with example you can edit