Sticky CSS Grid Items

If you’ve ever tried to put a sticky item in a grid layout and watched the item scroll away with the rest of the content, you might have come to the conclusion that position: sticky doesn’t work with CSS Grid. Fear not! It is possible to get these two layout concepts working together. All you likely need is one more line of CSS.

The Problem

Let’s start with the root issue you’re likely running into, because it’s not always obvious at first why your grid item isn’t sticking.

Suppose we’re putting together a template layout for articles on various candies. We have our title in the left-hand column of a grid layout, and have set the title to be sticky:

article {
  display: grid;
  grid-template-columns: 20em 1fr;
  grid-gap: 4em;
}

.title {
  position: sticky;
  top: 2rem;
}

Unfortunately, our title isn’t sticking to the top of the viewport, but instead scrolls away with the rest of the text:

See the Pen Blog post > grid + sticky > demo 1 by Melanie Richards (@somelaniesaid) on CodePen.

 

If we throw a border on our sticky title (or use a CSS Grid inspector), our root issue becomes more obvious:

See the Pen Blog post > grid + sticky > demo 2 by Melanie Richards (@somelaniesaid) on CodePen.

The CSS Grid item sizing algorithm has effectively sized the grid item (our sticky title) to fill the height of the grid slot it has been placed in. We don’t see any sticky effects because its computed height is the same as the content in the grid slot beside it.

Nitty gritty details on sizing

Things are about to get nerdy, skip to “How to fix it” if you just want the solution!

Because we didn’t use any CSS properties that specify how to size our grid items (we will get to these in a minute!), CSS Grid defaulted to its “normal” sizing algorithm when determining the sticky title’s size.

Our title, an h1

  • Is not a replaced element, such as an img, video, embed, iframe, etc. These have special sizing rules.
  • Does not have a “preferred aspect ratio”. Such an intrinsic aspect ratio can be set to particular elements by the user agent’s stylesheet, or by using the aspect-ratio property.

…therefore, the algorithm fell back to a “stretch” sizing scheme. This basically ensures that the box’s size in this dimension is set to fill the layout container it’s in (to simplify, the grid slot).

How to fix it

One way to address this is to specify an extrinsic height dimension for our sticky title, e.g. height: 10em, max-height: 50vh, whatever. Specifying such a literal height for our content is hacky though—we don’t want a specific height, we want the computed height to be just enough to accommodate the element’s contents. Instead we can change how this element is aligned to the grid slot.

We can specify one of the following:

  • align-self: this property, when specified on the sticky title, tells the element how to align itself to the block direction of the grid slot it’s in. align-self: start would work nicely in our example, as it will align the item to the “start” edge of the grid slot (in this context, the top edge).
  • align-items: this property, when specified on the article (our grid parent), tells each grid item how to align itself to the block direction of the grid slot it’s in.

(Note: the place-self and place-items shorthands will also work; these handle both block and inline axes)

It might be nice to align the text baseline of our sticky title and the text baseline of our first paragraph. If we set align-items: baseline; on the article, that forces the CSS Grid sizing algorithm to use a “fit-content” scheme. There’s some complexity there, but in our case, the algorithm used our grid item’s “max-content size”, or “the smallest size the box could take in that axis while still fitting around its contents”.

Because the sticky title is now sized according to its contents, we get the position: sticky behavior we’re after:

See the Pen Blog post > grid + sticky > demo 3 by Melanie Richards (@somelaniesaid) on CodePen.

Our updated styles:

article {
  display: grid;
  grid-template-columns: 20em 1fr;
  grid-gap: 4em;

  /* The new line we added! */
  align-items: baseline;
}

.title {
  position: sticky;
  top: 2rem;
}

And that’s it! Hope this helps you out of a sticky situation. 😏

Additional resources

Responses

My blog uses Webmentions. Responses from sites which likewise support Webmentions, such as Twitter or people’s personal sites, will show up here.

  • Greg Whitworth on

    Heard numerous folks hit this issue, even if you haven't hit this I recommend bookmarking this post.
  • Adrian Roselli on

    This seems swell. https://t.co/iNUFOBwgsB Post: melanie-richards.com/blog/css-grid-… I had always relied on align-self: start. Had never considered the baseline approach.
  • Reply from Lauri Lännenmäki on

    Haven't had this issue yet, but now I already know the solution to it! Thank you for the tip, Melanie 👍
  • Lauri Lännenmäki on

    #CSS Tip: Easy solution for dealing with 'position: sticky' grid-item. ☝️Example case: Article sidebar with links to different sections of the post.
  • Reply from Melanie Richards on

    Sure thing! 😊
  • Paul Scanlon on

    Perfect timing. I was actually tying to do this today. I gave up in the end but... wallop, this is so well explained too. Nice job 👏 twitter.com/somelaniesaid/…
  • Felquis G on

    awesome
  • Reply from Hap Hazard on

    That’s awesome!
  • alsacreations on

    Faire fonctionner position: sticky avec CSS Grid Layout ? C'est possible, @soMelanieSaid explique comment melanie-richards.com/blog/css-grid-…
  • Fatih Hayrioğlu on

    CSS grid içinde sticky kullanırken bu yazı aklımızda olsun. 💡 Sticky CSS Grid Items | Melanie Richards melanie-richards.com/blog/css-grid-…
  • Geoffrey Crofte 🔥 on

    Sticky CSS on Grid Items That's smart to use align-items to intrinsic size the grid item and be able to use sticky positionnent. No more hacky height. melanie-richards.com/blog/css-grid-…
  • Mattia Astorino on

    Little big #CSS tip here. twitter.com/somelaniesaid/…
  • Baldur Bjarnason on

    “Sticky CSS Grid Items - Melanie Richards” melanie-richards.com/blog/css-grid-…
  • Sean Curtis on

    This just gave me some inspiration to solve a pure css scroll hints (lines over the content, not under) thing I’ve been trying to get to work for years! Should be sleeping instead of coding at 2am though.
  • Phuoc Nguyen on

    A cool tip from @soMelanieSaid to make position: sticky work with #CSS Grid ❤️ melanie-richards.com/blog/css-grid-… #webdev #webdesign #CSSGrid #FrontEnd
  • Webmentry on

    Sticky CSS Grid Items #WebDesign via twinybots.ch melanie-richards.com/blog/css-grid-…
  • Big5 Network on

    Sticky CSS Grid Items #WebDesign via twinybots.ch melanie-richards.com/blog/css-grid-…
  • Chris Heilmann on

    👉🏻 “Sticky CSS Grid Items” 🔗 melanie-richards.com/blog/css-grid-… by @soMelanieSaid
  • AdPositivePrintable (F4F) on

    Sticky CSS Grid Items #WebDesign via twinybots.ch melanie-richards.com/blog/css-grid-…
  • Frontend Daily 🚀 on

    Sticky CSS Grid Items: melanie-richards.com/blog/css-grid-… (How to get position sticky working on a grid item without setting a hacky height.)
  • Pinboard Popular on

    Sticky CSS Grid Items | Melanie Richards melanie-richards.com/blog/css-grid-…
  • Joan León 🏞⚡️ on

    Sticky CSS Grid Items melanie-richards.com/blog/css-grid-… by @soMelanieSaid #css #cssCrafters #Grid
  • JAC Graphic & Web Design Dept on

    Sticky CSS Grid Items | Melanie Richards melanie-richards.com/blog/css-grid-…
  • by on

    submitted by /u/magenta_placenta [link] [comments]
  • Bramus! Sticky CSS Grid Items on

    Melanie Richards: If you’ve ever tried to put a sticky item in a grid layout and watched the item scroll away with the rest of the content, you might have come to the conclusion that position: sticky doesn’t work with CSS Grid. Fear not! It is possible to get these two layout con…
  • コムテ on

    [CSS] Gridレイアウトでスクロール時に固定させる方法。align-items: baseline;を追加する。 #CSS Sticky CSS Grid Items | Melanie Richards melanie-richards.com/blog/css-grid-…
  • Speckyboy on

    Sticky CSS Grid Items by @soMelanieSaid melanie-richards.com/blog/css-grid-…
  • GoDaddy Pro on

    If you've ever struggled to create a sticky item in a grid layout, then you need to check out this blog from @soMelanieSaid! Thanks for sharing your expertise, Melanie! melanie-richards.com/blog/css-grid-…
  • admin Weekly News for Designers № 572 on

    2020 Web Design Year in Review – A look back at some important and interesting developments that impacted web designers this past year. Search Engine Optimization Checklist (PDF) – Use this handy reference to solve your most tedious SEO issues. Wavelry – Create your own custom …
  • I ❤️ Javascript | Typescript | Angular on

    melanie-richards.com/blog/css-grid-…
  • Friday Front-End on

    Sticky CSS Grid Items, by @soMelanieSaid melanie-richards.com/blog/css-grid-…
  • ながしまきょう on

    グリッド項目の位置を半固定する。または、グリッドによる自動サイズ調整を制御する方法。 melanie-richards.com/blog/css-grid-…
  • Mazik Solutions on

    Sticky CSS Grid Items melanie-richards.com/blog/css-grid-…
  • Yohan J. Rodríguez on

    #CSS #Automated | Sticky CSS Grid Items melanie-richards.com/blog/css-grid-…
  • Adactio Links on

    Sticky CSS Grid Items | Melanie Richards melanie-richards.com/blog/css-grid-…
  • Vitaly Kondratiev on

    Useful technique: sticky css grid items melanie-richards.com/blog/css-grid-…
  • Joulse on

    Sticky CSS Grid Items melanie-richards.com/blog/css-grid-…
  • Front-End Front on

    Sticky CSS Grid Items melanie-richards.com/blog/css-grid-…
  • Pablo Lara H on

    Sticky CSS Grid Items by Melanie Richards @soMelanieSaid #sticky #css #grid #webdev melanie-richards.com/blog/css-grid-…
  • Guillaume L. on

    Sticky CSS Grid Items: melanie-richards.com/blog/css-grid-…
  • admin WDRL — Edition 287: A new year, a new start and nothing ground changing. on

    Hey, Welcome to another new year, 2021. WDRL is now seven and a half year old already and the first edition had about twenty email subscribers. What was in there? We had webfont loading behaviour, Speedcurve, a HTML validator, GrumpIcon which created PNG fallbacks for SVG icons v…
  • Veerle Pieters on

    Sticky CSS Grid Items Melanie Richards explains how to get position sticky working on a grid item without setting a hacky height. Great tip! melanie-richards.com/blog/css-grid-…
  • Julian on

    Sticky CSS Grid Items | Melanie Richards melanie-richards.com/blog/css-grid-…