Is it possible to have an element with effectively position: fixed
on the x-axis, but position: absolute
on the y-axis, without JavaScript? See this snippet for an example that uses JavaScript:
$(window).scroll(function(){
var $win = $(window);
$('#box1').css('top', 20 -$win.scrollTop());
$('#box2').css('left', 20 -$win.scrollLeft());
});
html, body {
width: 2000px;
height: 2000px;
}
.box {
width: 400px;
height: 80px;
background: gray;
position: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box1" class="box" style="left:20px;top:20px;">
My position-x is fixed but position-y is absolute.
</div>
<div id="box2" class="box" style="left:20px;top:120px;">
My position-x is absolute but position-y is fixed.
</div>
<div id="box3" class="box" style="left:20px;top:220px;">
Im positioned fixed on both axis.
</div>
You can use margin-top
and position: sticky
. It will give you the result you want.
$(window).scroll(function() {
var $win = $(window);
$('#box1').css('top', 20 - $win.scrollTop());
$('#box2').css('left', 20 - $win.scrollLeft());
});
html,
body {
width: 2000px;
height: 2000px;
}
.box {
width: 400px;
height: 80px;
background: gray;
position: fixed;
}
#box3 {
margin-top: 220px; /* use 'margin-top' instead of 'top' */
position: sticky;
left: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box1" class="box" style="left:20px;top:20px;">
My position-x is fixed but position-y is absolute.
</div>
<div id="box2" class="box" style="left:20px;top:120px;">
My position-x is absolute but position-y is fixed.
</div>
<div id="box3" class="box">
Im positioned fixed on both axis.
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With