Fixed position but relative to container

后端 未结 25 1612
独厮守ぢ
独厮守ぢ 2020-11-21 23:52

I am trying to fix a div so it always sticks to the top of the screen, using:

position: fixed;
top: 0px;
right: 0px;

However,

25条回答
  •  醉话见心
    2020-11-22 00:32

    With pure CSS you can't manage to do it; at least I haven't. However you can do it with jQuery very simply. I'll explain my problem, and with a little change you can use it.

    So for a start, I wanted my element to have a fixed top (from top of the window), and a left component to inherit from the parent element (because the parent element is centered). To set the left component, just put your element into the parent and set position:relative for the parent element.

    Then you need to know how much from the top your element is when the a scroll bar is on top (y zero scrolled); there are two options again. First is that is static (some number) or you have to read it from the parent element.

    In my case it's 150 pixels from top static. So when you see 150 it's how much is the element from the top when we haven't scrolled.

    CSS

    #parent-element{position:relative;}
    #promo{position:absolute;}
    

    jQuery

    $(document).ready(function() { //This check window scroll bar location on start
        wtop=parseInt($(window).scrollTop());
        $("#promo").css('top',150+wtop+'px');
    
    });
    $(window).scroll(function () { //This is when the window is scrolling
        wtop=parseInt($(window).scrollTop());
        $("#promo").css('top',150+wtop+'px');
    });
    

提交回复
热议问题