2

I am trying to create a CSS class that's supposed to take the remaining space of a flex-container, regardless of the amount of flex-items. Meaning that a fixed percentage width or flex-basis is not an option.

According to this answer, applying .flex-item { flex-grow: 1; flex-basis: 0; } should do the trick, but as you can see here, it is not working when some items have a padding or borders, even after setting box-sizing to border-box.

Is this a bug or desired behavior? Is it possible to specify equal width for any number of flex items, regardless of padding and borders?

Community
  • 1
  • 1
Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90

1 Answers1

6

This is not a bug. It is the desired behavior.

When you have a bunch of flex-children, and apply flex-basis: 0 and flex-grow: 1 to them, the following steps are being taken by the browser:

  • Render text and other content the flex-children have
  • Apply padding, borders and margins (taking the box-sizing into account)
  • Starting with the smallest flex-child (because of flex-basis: 0) keep adding width to the items until the container is full (flex-grow: 1).

That last step is where your problem lies. The browser doesn't force the elements to first be 0 pixels wide and all grow evenly. The browser simply starts with the smallest flex-child, giving it more width until it has grown as wide as the second smallest. At that point both of these flex-children will both grow evenly. And so forth, adding width until all space is distributed. This is also why box-sizing: border-box seems to not working.

You can fix this by adding a container to each of the flex-items, which has the border-box part applied. See this Fiddle. The contents have been wrapped into another div, and the styles have been applied to it as well (except for the flex-specific properties, of course).

Gust van de Wal
  • 5,211
  • 1
  • 24
  • 48