Fixed position but relative to container

后端 未结 25 1605
独厮守ぢ
独厮守ぢ 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

    2019 SOLUTION: You can use position: sticky property.

    Here is an example CODEPEN demonstrating the usage and also how it differs from position: fixed.

    How it behaves is explained below:

    1. An element with sticky position is positioned based on the user's scroll position. It basically acts like position: relative until an element is scrolled beyond a specific offset, in which case it turns into position: fixed. When it is scrolled back it gets back to its previous (relative) position.

    2. It effects the flow of other elements in the page ie occupies a specific space on the page(just like position: relative).

    3. If it is defined inside some container, it is positioned with respect to that container. If the container has some overflow(scroll), depending on the scroll offset it turns into position:fixed.

    So if you want to achieve the fixed functionality but inside a container, use sticky.

提交回复
热议问题