Sticky Labels in an Overflow-X div

I currently have a component like in the picture. When I scroll left/right only the overflow-x div scrolls. The div contains a list of numbers at the top, that you can see in blue in the second picture At the moments the numbers are in an absolute overlay like so:
{renderSegments.map((segment, index) => (
<>
<div
className="absolute h-full bg-sky-500 transition-opacity"
style={{
left: `${segment.start}px`,
width: `${segment.width}px`,
opacity: segment.opacity,
}}
/>

<div
className="absolute top-1/2 -translate-y-1/2 text-xs text-white"
style={{
left: `${segment.start + 3}px`,
zIndex: 10,
}}
>
{segment.charges}
</div>
)}
</>
))}
{renderSegments.map((segment, index) => (
<>
<div
className="absolute h-full bg-sky-500 transition-opacity"
style={{
left: `${segment.start}px`,
width: `${segment.width}px`,
opacity: segment.opacity,
}}
/>

<div
className="absolute top-1/2 -translate-y-1/2 text-xs text-white"
style={{
left: `${segment.start + 3}px`,
zIndex: 10,
}}
>
{segment.charges}
</div>
)}
</>
))}
I would like for the numbers to remain sticky to the left border of the div when scrolling to the right. In picture 3 if I scroll more to the right the 1 should stay fixed until the next number. I assume that hiding the numbers when the next one is close is not something I can (should) do in CSS but I was wondering if there was a way for the elements to stay sticky using CSS. Anyone has anything I can try?
No description
No description
No description
2 Replies
HansM
HansM•4mo ago
sticky is exactly what you're looking for I suppose. position: sticky; and left or right: 0; to the number and position: relative; to the whole container that scrolls. These things are quite common for vertical scroll, but work horizontally all the same 🙂
Rägnar O'ock
Rägnar O'ock•4mo ago
Yeah, just slap a position: sticky on it and set the stuck margins with inset

Did you find this page helpful?