(╯°□°)╯

CSS - Why are you like this?


It is always a learning journey with CSS, as there are many “edge cases” and they are often infuriating to resolve.

Why does it behave this way? How could I have known this?!

I chanced upon this unexpected behavior when I was trying to write a responsive tabs component.
To be explicit, I want to design my component to:

  • Grow as much as you need, up to your max-width
  • But if your parent is smaller than your max-width, then your parent’s width is your max-width

Demo

Try resizing the demo below to see for yourself.
The width of the “undesired” example maintains at its max-width even when the parent has shrunk smaller than that.

Desired behavior
Lorem ipsum dolor sit amet, consectetur adipiscing elit
Undesired behavior
Lorem ipsum dolor sit amet, consectetur adipiscing elit

Solution

The conditions for this problem are:

  • The parent container uses display: flex or display: grid
  • The immediate child uses flex-grow: 1 as it wants to use as much width as it needs
  • The content of the immediate child is not pure text

In the demo above, I’m only using text as the content of the child. This would normally work fine, but it breaks in a more complex setup with nested children using different displays, or contains images etc. To “emulate” this, I’m using white-space: pre in the demo to force text not to overflow into a new line.

For a display: flex parent, you can solve this by adding min-width: 0 to the immediate child. This is apparently necessary because min-width: auto is the default value. In the context of a flexbox, this effectively means that min-width = max-width.

You can see all this in action from the demo above using your browser dev tools.

Actual use case

If you’re curious how this came about, I wrote the responsive tab component here.