skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

        <div className="sticky top-0 z-30">
          <div
            className="grid h-5 grid-cols-[repeat(240,32px)] items-baseline overflow-x-auto text-neutral-600"
          >
            {[...Array(24)].map((_, i) => (
              <div
                className="sticky left-0 whitespace-nowrap pl-1.5 pt-1 align-text-bottom text-xs dark:text-neutral-300"
                style={{
            gridColumn: i === 0 ? 1 : (24 * i * 2) + 1,
                }}
              >
                {date}
                <div className="absolute bottom-0.75 left-0 h-2/3 w-0.5 bg-neutral-300" />
              </div>
            ))}
          </div>
          <div
            className="grid h-5 grid-cols-[repeat(120,64px)]"
          >
            {[...Array(7)].map((_, i) => (
              <div
                className="whitespace-nowrap py-1 text-xs dark:text-neutral-30"
                style={{
                  gridRow: 1,
                }}
              >
                {days}
              </div>
            ))}
          </div>
        </div>
    
    

  2. Change top-0 to left-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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search