- Published on
Make position fixed element take up space before scroll
- Authors
- Name
TLDR: Used React ref to track the height of the fixed element, then set that to the height of a position: relative
empty div.
Introduction
I used this to create a scroll over effect you can see if you scroll on my e-card website here. Edit: Removed this effect on website since if the fixed
element is smaller than the screen, those parts cannot be seen.
How I did it
My fixed element had a height that changes on certain conditions, so I used ResizeObserver
, however if you have an element with a static height, you can simply set the element height outside of the resize observer.
With fixed element of dynamic height
const elementRef = useCallback((node: HTMLDivElement) => {
if (!node) return;
const resizeObserver = new ResizeObserver(() => {
setElementHeight(node.getBoundingClientRect().height)
});
resizeObserver.observe(node);
}, []);
With fixed element of static height
const elementRef = useCallback((node: HTMLDivElement) => {
if (!node) return;
setElementHeight(node.getBoundingClientRect().height)
}, [deps_go_here]);
With HTML
Finally, assign the ref to the fixed element, and give the placeholder div a low z-index. You could also use user-select: none
and pointer-events: none
instead of the z-index, to allow clicking through.
<div
ref={elementRef}
className={`fixed`}
>
{children}
</div>
<div style={{ height: elementHeight }} className='relative -z-30' ></div>
I used Tailwind here, but you can do the same with css position: fixed
and position:relative; z-index: -30