I’m really struggling with working out how to make each element of the grid sticky on horizontal scroll. I’ve tried so many combinations but the {date} is never sticky. I’ve tried adding overflow-x-scroll
to the parent, and changing items-baseline
with items-stretch
on both parent and child components. No matter what, the date is never sticky.
Any help would be hugely appreciated
<div
className="items-baseline grid h-5 grid-cols-[repeat(240,32px)] text-neutral-600 overflow-x-auto"
>
{[...Array(24)].map((_, i) => (
<div
key=key
className="sticky top-0 whitespace-nowrap text-xs pt-2 dark:text-neutral-30"
style={{
gridColumn: i === 0 ? 1 : (24 * i * 2) + 1,
}}
>
{date}
</div>
))}
</div>
2
Answers
Thank you for your answer. I actually ended up finding out about left-0 before and then I tried out your solution, and for some reason it's still not working. I also have a sticky at the top level for vertical scroll but I don't think it's affecting the horizontal scroll.
Here's the full code snippet:
Change
top-0
toleft-0
.Sticky elements are "positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor . . . based on the values of top, right, bottom, and left" – MDN Docs. Because the scrolling is happening horizontally, we need to tell each child to stick when it is 0 (or however many) pixels away from the left (or right) side. You would only see the effects of
top-0
if there was some vertical scrolling.Here is a working example in a Tailwind Playground.