CSS グリッドレイアウトを利用時にposition: sticky
を効かせるにはstickyを指定するセレクターでalign-self: start;
等を指定し高さをストレッチしないようにする必要がありますが、
なぜかalign-self: start;
を指定しても効かなかった事象があったので対応法をメモ📝
再現コード
以下のようなサイドメニューとメインコンテンツがあるようなhtmlで
<div class="root"> <div class="main-with-sidemenu"> <aside class="main-with-sidemenu__sidemenu is-sticky"> <h1>Side Menu</h1> </aside> <main class="main-with-sidemenu__main"> <h1>Main Content</h2> </main> </div> </template> </div>
サイドメニューをスクロールしても固定するためにposition: sticky
するようなCSSを記載したときになぜかposition: sticky
が効かなくなりました🤔
.root { overflow: hidden; } .main-with-sidemenu { display: grid; grid-template-columns: 2fr 8fr; grid-template-areas: "sidemenu main"; } .main-with-sidemenu__sidemenu { background-color: blue; grid-area: sidemenu; } .main-with-sidemenu__sidemenu.is-sticky { top: 0px; align-self: start; position: sticky; } .main-with-sidemenu__main { grid-area: main; height: 1200px; background-color: gray; }
CODEPENはこちら
See the Pen position-sticky-not-working-sample by madogiwa (@madogiwa0124) on CodePen.
原因・解決方法
祖先要素でoverflow: hidden;
が効いていたのが原因でposition: sticky
が効いていなかったので、以下の記述を削除したら動作するようになりました!
.root { overflow: hidden; }
あんまりちゃんと分かってないですが、overflow: hidden
が設定されていると想定外の動きになるようです。。。
Simply put, scrolling the ancestor will cause the sticky to stick, scrolling the window will not. This is expected with overflow: auto and overflow: scroll, but often causes confusion with overflow: hidden. GitHub - wilddeer/stickyfill: Polyfill for CSS `position: sticky`