Fixed-Height Item Virtualization
What you'll learn: How to implement virtual scrolling when every list item has the same height, making calculations significantly simpler and faster.
The Simplest Virtualization Scenario
When all your list items have identical heights, virtual scrolling becomes straightforward math. Instead of measuring each item individually, you can use multiplication and division to instantly calculate which items should be visible.
Think of it like a perfectly aligned stack of identical boxes. If each box is 50px tall and your viewport shows 200px, you know exactly 4 boxes fit without measuring each one individually.
Why Fixed Heights Make Things Easy
With fixed-height items:
- Scroll position → Item index =
Math.floor(scrollTop / itemHeight) - Total scroll height =
itemCount * itemHeight - Item position =
itemIndex * itemHeight
No need to sum up heights or maintain position caches. Everything is instant arithmetic.
The Core Pattern
const itemHeight = 50; // Every item is 50px
const containerHeight = 400;
const scrollTop = container.scrollTop;
// Calculate visible range
const startIndex = Math.floor(scrollTop / itemHeight);
const visibleCount = Math.ceil(containerHeight / itemHeight);
const endIndex = startIndex + visibleCount;
// Set total scrollable height
container.style.height = `${items.length * itemHeight}px`;
// Position each visible item
visibleItems.forEach((item, i) => {
const index = startIndex + i;
item.style.transform = `translateY(${index * itemHeight}px)`;
});
All calculations are O(1) — they don't depend on the number of items or how far you've scrolled.
Key Takeaway: Fixed-height virtualization uses simple multiplication and division instead of complex measurements, making it the fastest and easiest form of virtual scrolling to implement correctly.