Sarah Tamar Lara
Sarah Tamar Lara

Reputation: 33

Understanding flex-basis in flex shorthand

I understand flex-grow: it allows a flex item to grow based on a ratio relative to the other flex items on the same row/column.

I understand flex-shrink: it allows a flex item to shrink based on a ratio relative to the other flex items on the same row/column.

I understand flex-basis: it overrules the main-size value and sets it's width (or height, depending on orientation).

However, I don't understand flex-basis: auto || 0 and the like.

Here is my code:

<div class="container">
  <div class="one item">Box 1</div>
  <div class="two item">Box 2</div>
  <div class="three item">Box 3</div>
</div>

and css:

.container {
  display: flex;
}

.item {
  border: solid red 1px;
  padding: 5px;
}

.one {
  flex: 1 0 100px;
}

.two {
  flex: 1 0 auto;
}

.three {
  flex: 1 0 auto;
}

I expected that all three boxes would be the same size, since they all are set to flex-grow: 1. However, not only is this not the case, Box one is bigger than either box and larger than 100px.

What is making the sizes be uneven despite the even ratio of flex-grow and the flex-basis of box 1 to be ignored?

Upvotes: 3

Views: 3475

Answers (1)

stephenhay
stephenhay

Reputation: 2874

This is an instance of "relative flex": The flex-basis of each flex item is used, and the remaining space is added to these.

100px just happens to be larger than the auto of the other two in your example; available space is added evenly to all boxes after taking the flex-basis into account.

This is what happens when box two has a larger intrinsic width than the 100px of box 1: http://jsbin.com/gakeju/1/

See http://www.w3.org/TR/css-flexbox-1/#valdef-flex-flex-basis

(Not your question, but to clarify: if you want the items to have space distributed to them without accounting for their (intrinsic) width, then you should set flex-basis to 0 (or 0%), i.e. flex: 1 0 0;. This would make the items in your example the same width, since all the boxes start with the same flex-basis and then get the space distributed to them.)

Upvotes: 4

Related Questions