解決策
固定表示と言えば、
position: fixed
これだと、固定する範囲を指定したい場合は、JSが必要。
position: absolute
でもできなくない。
でも
position: sticky
がスマートでしょう。
これらの違いは
で見てみよう。
absolute
The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.
developer.mozilla.org
This value creates a new stacking context when the value of z-index is not auto. The margins of absolutely positioned boxes do not collapse with other margins.
直近でrelative設定された祖先要素に対して相対的に配置される。
fixed
The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to the initial containing block established by the viewport, except when one of its ancestors has a transform, perspective, or filter property set to something other than none (see the CSS Transforms Spec), in which case that ancestor behaves as the containing block. (Note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) Its final position is determined by the values of top, right, bottom, and left.
developer.mozilla.org
This value always creates a new stacking context. In printed documents, the element is placed in the same position on every page.
Viewportで決められた初期ブロックから相対的に配置される。
sticky
The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.
developer.mozilla.org
This value always creates a new stacking context. Note that a sticky element “sticks” to its nearest ancestor that has a “scrolling mechanism” (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn’t the nearest actually scrolling ancestor. This effectively inhibits any “sticky” behavior (see the Github issue on W3C CSSWG).
通常のドキュメントフローに沿って配置される。固定要素は「スクローリングメカニズム」を持つ直近の祖先要素に「stick」される。
IE対応
例によって?!IEでは動かない。
以下を読み込めば大丈夫。
Deprecated!!
JSライブラリあるだと思って調べて辿り着いたらDeprectaed!!!
CSSでやった方が良いでしょう。