Difference between position:sticky and position:fi

2019-02-11 12:48发布

问题:

The documentation was pretty hard to understand since I am new to CSS. So can anyone please explain the actual difference between position:sticky and position:fixed? I would also appreciate an example.

I have gone through https://developer.mozilla.org/en-US/docs/Web/CSS/position and a few other articles, but I still don't get it.

回答1:

position: fixed always fixates an element to some position within its scrolling container or the viewport. No matter how you scroll its container, it will remain in the exact same position and not affect the flow of other elements within the container.

Without going into specific details, position: sticky basically acts like position: relative until an element is scrolled beyond a specific offset, in which case it turns into position: fixed, causing the element to "stick" to its position instead of being scrolled out of view. It eventually gets unstuck as it gets scrolled back toward its original position. At least, that's how I understand it in theory.

The reason why I want to avoid going into details is because position: sticky is brand new, experimental (as shown in the document you link to), and not finalized yet. Even what I've stated above may well change in the near future. You won't be able to use position: sticky yet anyway (hopefully this will change within the next year).

Mozilla recently presented its implementation of position: sticky here. It's highly worth a watch.



回答2:

See this self-explanatory example for better clarity. CODEPEN

Fixed Position:

  1. An element with fixed position is displayed with respect to the viewport or the browser window itself. It always stays in the same place even if the page is scrolled.

  2. It does not effect the flow of other elements in the page ie doesn't occupy any specific space(just like position: absolute).

  3. If it is defined inside some other container (div with or without relative/absolute position), still it is positioned with respect to the browser and not that container. (Here it differs with position: absolute).

Sticky Position:

  1. An element with sticky position is positioned based on the user's scroll position. As @Boltclock mentioned 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.