Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS-only position-x: fixed

Tags:

html

css

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>
like image 531
Max Avatar asked Sep 19 '25 22:09

Max


1 Answers

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>
like image 196
doğukan Avatar answered Sep 21 '25 12:09

doğukan