Sub topic 16
Why items refuse to shrink: min-width: 0
This chapter explains why a flex item sometimes overflows its container even though it has flex-shrink: 1, and how min-width: 0 fixes it. It assumes you know display: flex, the main axis, and the flex shorthand from earlier chapters.
The automatic minimum size
A flex item shrinks only down to its minimum size. For most elements, min-width defaults to auto. On a flex item in a row, auto resolves to the item's content size: the width of its longest unbreakable piece, such as a long word, an image, or text set to white-space: nowrap.
So flex-shrink can reduce an item's width, but never below that content size. When the container is narrower than the combined minimums, the items overflow.
The same rule applies on the cross axis and in column layouts. In a flex-direction: column container, the automatic minimum applies to height, so min-height: 0 is the fix there.
Reproducing the problem
Here a row holds a flexible title and a fixed button. The title uses white-space: nowrap, so its content size is the full length of the text.
.row {
display: flex;
gap: 0.5rem;
}
.row .title {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}You might expect the ellipsis to appear when the title is too long. It does not. The title's automatic minimum is the width of the whole unwrapped text, so it refuses to shrink and pushes the row wider than its parent.
The fix
Set min-width: 0 on the item that should shrink.
.row {
display: flex;
gap: 0.5rem;
}
.row .title {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}Now the title can shrink below its text width. Because overflow: hidden clips the extra text, text-overflow: ellipsis can draw the ….
Other ways to remove the minimum
Any overflow value other than visible also changes the automatic minimum to 0. That is why overflow: hidden on a flex item often fixes the problem on its own. Setting min-width: 0 is more explicit, and it does not clip anything unless you ask for it.
| Situation | Typical fix |
|---|---|
| Long text in a row item | `min-width: 0`, optionally with `overflow-wrap: anywhere` |
| Truncating with an ellipsis | `min-width: 0` plus `overflow: hidden` |
| Tall content in a column item | `min-height: 0` |
| Wide `pre` or table inside a flex item | `min-width: 0` on the item, `overflow: auto` on the content |
Exercise
A sidebar layout uses .layout { display: flex; } and .content { flex: 1; }. A <pre> block with a very long line inside .content makes the page scroll horizontally. What do you add to .content and pre so the code block scrolls on its own?
Show answer
Add min-width: 0 to .content so it can shrink below the width of the code, and add overflow: auto to pre so the long line scrolls inside the block instead of widening the page.