4

I'm trying to understand the following line.

flex: 0 1 50%

Now if the last value, flex basis was pixels the above would say that the item is not allowed to grow, but allowed to shrink and will be at maximum 50 pixels.

But with percentage in there instead, what are the relations. It will be maximum 50% of width, but eh, since it is not allowed to grow it will stay at 50 percent of...something

Curious what your interpretation is.

Thanks in advance, as we say in Sweden.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701

1 Answers1

4

Percentage lengths are relative to their containing blocks.

Therefore, if the flex container has a width of 200px, and the flex items are set to flex-basis: 50%, then each item will resolve to 100px.

Of course, in flex layout, flex-basis represents the initial main size or, the size before flex-grow and flex-shrink are applied.

You have flex-grow disabled, so nothing happens there.

But you have flex-shrink enabled, so the items will shrink below 100px when necessary to prevent an overflow of the container.

In this case, because all items are set to flex-shrink: 1, they will shrink in equal proportion.

article {
  display: flex;
  width: 200px;
  border: 1px solid black;
}

[one] > section {
  flex: 0 1 50px;
}

[two] > section {
  flex: 0 1 50%;
}

[three] > section {
  flex: 0 0 50%;
}


/* non-essential demo styles */
section {
  height: 50px;
  background-color: lightgreen;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}
<p>container width 200px in all cases</p>
<article one>
  <section><span>50px</span></section>
  <section><span>50px</span></section>
  <section><span>50px</span></section>
  <section><span>50px</span></section>
</article>

<hr>

<p><code>flex-shrink</code> enabled</p>

<article two>
  <section><span>50%</span></section>
  <section><span>50%</span></section>
  <section><span>50%</span></section>
  <section><span>50%</span></section>
</article>

<hr>

<p><code>flex-shrink</code> disabled</p>

<article three>
  <section><span>50%</span></section>
  <section><span>50%</span></section>
  <section><span>50%</span></section>
  <section><span>50%</span></section>
</article>

More details about percentages and flex-basis:

§ 7.2.3. The flex-basis property

Percentage values of flex-basis are resolved against the flex item’s containing block (i.e. its flex container); and if that containing block’s size is indefinite, the used value for flex-basis is content.

More details about percentage lengths in general:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701