<div class="container">
<div class="fixed-parent">
<p>Mr Fixed</p>
<div class="fixed-child">Fixed child with z-index: 3</div>
<div class="other-fixed-child">Fixed child with z-index 1</div>
</div>
<div class="subcontainer">
<div class="random-zindex">I have z-index: 2</div>
<div class="just-sitting-here">I'm just sitting here</div>
</div>
</div>
.container {
width: 680px;
height: 2000px;
margin: 30px auto;
font-size: 24px;
}
.subcontainer {
width: 100%;
position: relative;
}
.fixed-parent {
/* Try changing the position of this element to absolute. It will trigger some JS which emulates the behaviour of "position: fixed" without the stacking context. */
position: fixed;
width: 600px;
height: 400px;
background-color: #eee;
padding: 20px 40px;
}
p {
margin: 0 0 20px;
}
.fixed-child {
display: inline-block;
vertical-align: top;
position: relative;
width: 200px;
height: 200px;
padding: 20px;
background-color: pink;
z-index: 3;
}
.other-fixed-child {
display: inline-block;
vertical-align: top;
margin-left: 110px;
position: relative;
width: 200px;
height: 200px;
padding: 20px;
background-color: lightblue;
z-index: 1;
}
.random-zindex {
position: absolute;
top: 400px;
left: 200px;
z-index: 2;
width: 260px;
height: 260px;
padding: 20px;
background-color: palegreen;
}
.just-sitting-here {
position: absolute;
top: 780px;
left: 300px;
width: 180px;
height: 180px;
padding: 10px;
background-color: #fafbac;
}
$(document).on('scroll', function(){
if ($('.fixed-parent').css('position') !== 'fixed') {
$('.fixed-parent').offset({top: $(document).scrollTop(), left: $('.fixed-parent').position().left });
}
})
This Pen doesn't use any external CSS resources.