Sub topic 4
The scroll container, the spacer, and positioned rows
A virtual list is built from three nested elements. This chapter explains what each one does, which CSS properties it needs, and what breaks when one is missing. The next chapter covers how to calculate which rows to render.
You should already know basic CSS positioning (relative, absolute), how overflow creates a scrollable box, and how React components render from props.
The problem the structure solves
A normal long list has one real DOM node per row. The browser sizes the scrollbar from the total height of those nodes, so the scroll range comes for free.
A virtual list mounts only the 20 or so rows near the viewport, so the browser no longer has the content it would use to size the scrollbar. The structure in this chapter has to supply three things:
- A scrollbar whose length and position match the full list.
- A way to place each mounted row where it would be in the full list.
- Stable positions, so mounting or unmounting a row never shifts its neighbours.
The three layers
Each layer has one job.
| Layer | Element | Key styles | Job |
|---|---|---|---|
| Scroll container | Outer `div` | Fixed `height`, `overflow: auto` | Defines the visible window and owns `scrollTop` |
| Spacer | Inner `div` | `height` = total list height, `position: relative` | Gives the container its full scroll range and acts as the positioning context |
| Rows | One `div` per visible item | `position: absolute`, `top` or `transform`, fixed `height` | Appear at their true offset inside the spacer |
The scroll container
The container is the element that actually scrolls. It needs two things.
- A bounded height. Without a fixed
height(or amax-height, or a flex or grid parent that constrains it), the container grows to fit its content. It then never overflows, never scrolls, and the layout stops being virtual. The container's height is also an input to the visible-range calculation, so you either know it in advance or you measure it. overflow: auto(orscroll). This makes the browser clip the content and expose a scrollbar when the content is taller than the box.
The container is also where you read scrollTop, the number of pixels the content has been scrolled up. In React you usually read it from the onScroll event with e.currentTarget.scrollTop. Use currentTarget, not target, because scroll events from the container fire on the container itself and currentTarget is always the element your handler is attached to.
Virtualization libraries do not have to use a div you render. TanStack Virtual accepts any scroll element through getScrollElement, and it can also use the window. The structure is the same either way.
The spacer
The spacer is an empty-looking box whose only purpose is its size. Set its height to the total height of all rows:
spacerHeight = items.length * rowHeightFor 50,000 rows of 28px, the spacer is 1,400,000px tall. The container is 400px tall, so the browser reports a scrollHeight of 1,400,000 and draws a scrollbar thumb that represents about 0.03% of the track. Dragging the thumb to the middle sets scrollTop near 700,000, exactly as it would in a real full-length list.
The spacer also needs position: relative. An absolutely positioned element is placed relative to its nearest positioned ancestor. If the spacer is not positioned, the rows look further up the tree. They may attach to the scroll container (if you positioned that), or to the page body. In both cases top: 1600px no longer means "1600px from the start of the list".
Size limits
Browsers cap the maximum height of an element. The limit differs by engine and version. It is on the order of 17 million pixels in Firefox and about 33 million in Chrome. A list of one million rows at 35px needs 35 million pixels and can exceed it. If you hit this, the spacer silently stops growing and the bottom of the list becomes unreachable. Typical fixes are pagination, or a library or custom code that scales scroll offsets. Treat this as a reason to question a million-row list in the first place.
Positioned rows
Each mounted row is placed with position: absolute inside the spacer. There are three reasons.
- No reflow cascade. An absolutely positioned element is out of normal flow. Mounting row 42 does not push row 43 down, and unmounting row 38 does not pull row 39 up.
- Position is a pure function of the index. Row
iis ati * rowHeight, regardless of which other rows are currently mounted. - Rows can mount in any order. After a fast scroll, a completely different set of rows can mount with no repositioning of the old ones.
You can express the offset with top or with transform: translateY(...):
| Approach | Example | Trade-off |
|---|---|---|
| `top` | `top: i * rowHeight` | Simple to read and debug. Changing `top` can trigger layout. |
| `transform` | `transform: translateY(${start}px)` | Does not affect layout and can be handled by the compositor. Creates a stacking context per row, which matters if rows contain popovers or `z-index` content. |
TanStack Virtual's examples use transform, and the hand-written list in this tutorial uses top. Both are valid. For a hand-written fixed-height list, top is the easier one to reason about.
Rows also need left: 0 and right: 0 (or width: 100%). An absolutely positioned div has no width from normal flow, so without them it shrinks to fit its text.
A minimal frame
This component renders the three layers with a hard-coded window of rows. It has no scroll handling yet. It is useful for opening dev tools and checking that the structure behaves as described.
type ScrollFrameProps = {
count: number;
rowHeight: number;
height: number;
first: number;
last: number;
};
export function ScrollFrame({ count, rowHeight, height, first, last }: ScrollFrameProps) {
const rows = [];
for (let i = first; i <= last; i++) {
rows.push(
<div
key={i}
style={{
position: "absolute",
top: i * rowHeight,
left: 0,
right: 0,
height: rowHeight,
boxSizing: "border-box",
borderBottom: "1px solid #ddd",
}}
>
Row {i}
</div>
);
}
return (
<div style={{ height, overflow: "auto", border: "1px solid #999" }}>
<div style={{ height: count * rowHeight, position: "relative" }}>{rows}</div>
</div>
);
}
// Example: <ScrollFrame count={50000} rowHeight={28} height={400} first={0} last={15} />With this example, only 16 rows exist in the DOM, yet the scrollbar behaves as if all 50,000 existed. Scroll down and the rows disappear off the top, then you see blank space. That is expected. Nothing yet updates first and last as scrollTop changes, which is the next chapter's subject.
Note boxSizing: "border-box" on the row. With the default content-box, the 1px border would be added to the 28px height, making each row 29px tall. The rows would then overlap the next row's position by 1px each, and the mismatch would grow with the index.
Common errors
- Everything renders and the page scrolls instead. The container has no bounded height, so it grows with the spacer. Set a fixed
heightor constrain it through a flex or grid parent withmin-height: 0. - Rows pile up at the top, or sit in the wrong place. The spacer is missing
position: relative, so rows are positioned against a different ancestor. - The scrollbar is too short. The spacer height was computed from the number of rendered rows instead of the total item count.
- Rows have the wrong width. The row has no
left/rightorwidth. - Rows drift or overlap. The real row height differs from
rowHeight, usually from borders, margins, or padding. Absolute positioning ignores margins between rows, so spacing must be built into the row height. - The scrollbar is missing at the bottom of a flex layout. A flex child defaults to
min-height: auto, so it will not shrink below its content. Addmin-height: 0to the scroll container.
Exercise
A list has 50,000 items. Each row is 28px tall, and the scroll container is 420px tall. (a) What height should the spacer have? (b) What top value does row 1000 get? (c) Roughly how many rows fit in the container at once, before overscan? (d) What goes wrong if you forget position: relative on the spacer?
Show answer
(a) 50,000 x 28 = 1,400,000px. (b) 1000 x 28 = 28,000px. (c) 420 / 28 = 15 rows exactly, so 15 rows fit fully, and a scroll position that is not a multiple of 28 can show a 16th row partially. (d) Rows are positioned against the nearest positioned ancestor above the spacer, or the page, instead of the spacer, so their top values no longer mean "distance from the start of the list". Rows appear at wrong places or outside the container.