How I fixed a sticky element not working in my Next.js / Tailwind CSS app with a grid layout
I started with the following Tailwind CSS / React code and sticky positioning didn't work:
<div className="grid grid-cols-12 gap-4 min-h-screen mt-16 pt-3">
<main className="flex flex-col col-start-2 col-span-8">{children}</main>
<aside className="sticky mt-14 top-20">ASIDE CONTENT</aside>
</div>
After reading this article I realized I need to apply align-self: start; to my aside element so I added the self-start class to:
<div className="grid grid-cols-12 gap-4 min-h-screen mt-16 pt-3">
<main className="flex flex-col col-start-2 col-span-8">{children}</main>
<aside className="sticky mt-14 top-20 self-start">ASIDE CONTENT</aside>
</div>
That wasn't enough to solve the problem, though. I asked ChatGPT and he said, among other things:
The sticky element's ancestors must not have overflow properties set to hidden, scroll, or auto.
I checked my code and, bingo, it looks like I had overflow-x: hidden; applied to my body element. Most likely from when I first set up my Next app with create-next-app. I commented it out and sticky positioning started to work.
html,
body {
max-width: 100vw;
/* overflow-x: hidden; */
}