Pin element like position: fixed but inside its parent not the viewport

后端 未结 3 963
一向
一向 2020-12-07 05:22

I\'ve looked around and it seems like a no-go, but I ask just in case.

Is it possible to create a sticky sidebar that follows you down the page but which stays insid

相关标签:
3条回答
  • 2020-12-07 05:36

    What you should do is to set the parent to have position: relative and the sidebar to have position: absolute. This way the sidebar will be relatively positioned in respect to the parent.

    example css:

     #parent {
       position: relative;
     }
     #sidebar {
       position: absolute;
       top: 10px;
     }
    
    0 讨论(0)
  • 2020-12-07 05:39

    Is it possible to create a sticky sidebar that follows you down the page but which stays inside of its container element [using HTML/CSS only]?

    Like this:
    http://codepen.io/jamesdarren/full/ivmcH
    ... but without the JavaScript.

    The answer is: At the present time, it depends on your browser.

    CSS has an experimental positioning value named sticky.

    By setting your sidebar to position: sticky it can remain fixed inside its parent container and the viewport, as opposed to just the viewport.

    Here's how Google Developers describes it:

    position: sticky is a new way to position elements and is conceptually similar to position: fixed. The difference is that an element with position: sticky behaves like position: relative within its parent, until a given offset threshold is met in the viewport.

    Here's MDN's take:

    Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.

    Currently, however, only Firefox and Safari support sticky positioning.

    Here are two demos of position: sticky (FF & Safari only):
    http://html5-demos.appspot.com/static/css/sticky.html
    http://jsfiddle.net/daker/ecpTw/light/

    Here's a position: sticky polyfill:
    https://github.com/filamentgroup/fixed-sticky

    from the polyfill readme:

    The most overlooked thing about position: sticky is that sticky elements are constrained to the dimensions of their parent elements.


    Lastly, should you decide to loosen your language constraints to allow scripting, here's a simple, effective and reliable solution for a sticky sidebar:

    Tether

    Tether is a JavaScript library for efficiently making an absolutely positioned element stay next to another element on the page.

    Tether includes the ability to constrain the element within the viewport, its scroll parent, any other element on the page, or a fixed bounding box.

    http://github.hubspot.com/tether/

    0 讨论(0)
  • 2020-12-07 05:58

    You could try this: http://leafo.net/sticky-kit/

    And just use a simple javascript call for your sidebar

    $("#sidebar").stick_in_parent();
    
    0 讨论(0)
提交回复
热议问题