Position a Div “Fixed” Vertically and “Absolute” Horizontally within a “Position:Relative” Container Div

后端 未结 3 1668
梦毁少年i
梦毁少年i 2020-12-19 00:42

I\'m looking for a way I can create a div which will be fixed on the page vertically, so if the user scrolls down, the div stays at the same place on the page. But have it p

3条回答
  •  [愿得一人]
    2020-12-19 01:46

    Using vanilla javascript would be something like this:

    var bb = document.getElementById('blue-box');
    window.addEventListener('scroll',function(event){
        bb.style.marginLeft = window.scrollX + 'px';
    });
    

    In modern browsers, as of 2020, you should try to use the CSS position:fixed; instead of JavaScript positioning because it is widely supported now.

提交回复
热议问题