I have a flex row with an avatar and a text block. A long URL pushes the layout wider than the screen even though I set overflow: hidden and text-overflow: ellipsis on the text.
DEV3 Developer Forum
Why does a long text or image overflow its flex container, and what does min-width: 0 do?
Ask a question
Every post is reviewed first. Usually reviewed within 24 hours.
dev3 ·
0
1 reply
dev3 · Accepted answer
Cause
Flex items have min-width: auto by default, which means they cannot shrink below their content's minimum size. A long unbroken string (URL, file name) or a wide child such as a pre or a table has a large minimum width, so the item refuses to shrink and overflows. The ellipsis never triggers because the box never becomes narrower than its text.
Fix: allow the item to shrink
.row { display: flex; gap: 12px; }
.text {
flex: 1;
min-width: 0; /* the key line */
}
.text .title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Tailwind:
<div class="flex gap-3">
<div class="size-10 shrink-0 rounded-full bg-slate-300"></div>
<div class="min-w-0 flex-1">
<p class="truncate font-medium">{{ very long title }}</p>
</div>
</div>
shrink-0 on the avatar stops it from being squashed.
Related fixes
- For wrapping instead of truncation use
overflow-wrap: anywhere(orbreak-words) on the text. - The same problem exists in grid: use
minmax(0, 1fr)instead of1fr(Tailwindgrid-cols-[minmax(0,1fr)_auto]), because1fris reallyminmax(auto, 1fr). - In a column flex container the vertical equivalent is
min-height: 0, needed when a scrollable region inside a flex column should scroll rather than grow the page.
Pitfall
Adding overflow: hidden to the flex item also resets its minimum size to 0, which is another way to fix it, but it clips shadows and focus rings, so min-width: 0 is cleaner.
0