Tabs
When tabs overflow into a More menu, the selected tab always keeps its place on the strip.
The problem
When tabs don’t fit, they go into a More menu from the end. The usual bug: you select a tab near the end, the window narrows, and your tab disappears into the menu. Now nothing on the strip looks selected, and the content below has no visible label.
The second bug is at the edge. A strip sitting right at the boundary flips between “everything fits” and “one in More” as a scrollbar comes and goes.
What I concluded
The fit is greedy, with room reserved for the More button. If the selected tab didn’t make it, tabs are dropped from the end until it fits, and then it goes back in at its own position, not tacked on the end.
function fitTabs(widths, room, more, selected) {
const total = widths.reduce((a, b) => a + b, 0);
if (total <= room) return widths.map((_, i) => i);
const inline = [];
let used = more;
for (let i = 0; i < widths.length; i++) {
if (used + widths[i] > room) break;
inline.push(i);
used += widths[i];
}
if (!inline.includes(selected)) {
while (inline.length && used + widths[selected] > room)
used -= widths[inline.pop()];
inline.push(selected);
inline.sort((a, b) => a - b);
}
return inline;
}
Once something is in More, a tab only comes back out when there’s about a scrollbar’s width to spare. That slack is what stops the flicker.
Rules
- The selected tab is never hidden. Its neighbours give way instead.
- It keeps its own position. Order on the strip always matches order in the list.
- Reserve room for More. The button is part of the fit, not an afterthought.
- Slack before coming back. Demand extra room before showing everything again.
- It’s still a tablist. Arrows move between visible tabs, More is the last stop, and picking a tab from the menu pulls it onto the strip with focus following.
What you get
A strip that works at any width without ever losing track of where you are. The same fit, with a search box reserved instead of a selected tab, drives the filter bar.
The demo shows the fit: narrow it with Photos selected and its neighbours give way. Related: Filters, URL state.