2

I am playing around with Flexbox in an attempt to learn it on a fundamental level. I am confused by inconsistent results from independent usage of flex-grow and width on flex items.

Suppose I have the following HTML:

<div class="flex-container">
  <div id="flex-item-1">1</div>
  <div id="flex-item-2">2</div>
</div>

and the following CSS:

.flex-container {
  display: flex;
}

/* 
Within #flex-item-1 and #flex-item-2, toggle between
flex-grow and width to view the different resultant widths 
*/

#flex-item-1 {
  flex-grow: 3;
  background-color: tomato;
  width: 75%;
}

#flex-item-2 {
  flex-grow: 1;
  background-color: pink;
  width: 25%;
}

When the width CSS properties for #flex-item-1 and #flex-item-2 are active but the flex-grow properties aren't, you can see that the grid lines (made by the HTML and CSS code below) line up with #flex-item-1 and #flex-item-2 perfectly.

<!-- 12-column grid lines -->
<div class="flex-container">
    <div class="col">1</div>
    <div class="col">2</div>
    <div class="col">3</div>
    <div class="col">4</div>
    <div class="col">5</div>
    <div class="col">6</div>
    <div class="col">7</div>
    <div class="col">8</div>
    <div class="col">9</div>
    <div class="col">10</div>
    <div class="col">11</div>
    <div class="col">12</div>
</div>
.col {
    box-sizing: border-box;
    border-left: 1px solid green;
    width: 8.333333%;
    height: 100px;
}

enter image description here

However, when the flex-grow properties are active and the width properties aren't, the flex items don't line up with the grid exactly:

enter image description here

Why is this?

Feel free to play around with this example on this Codepen.

Shandy Sulen
  • 301
  • 2
  • 17

2 Answers2

4

You need to set the flex-basis property on your flex-items to 0%

#flex-item-1 {
  flex-basis: 0%;
  flex-grow: 3;
  background-color: tomato;
/*   width: 75%; */
}

#flex-item-2 {
  flex-basis: 0%;
  flex-grow: 1;
  background-color: pink;
/*   width: 25%; */
}

It specifies the initial size of the flex item, before any available space is distributed according to the flex factors. When omitted from the flex shorthand, its specified value is the length zero. Source: mdn

Stackblitz example

Martin Godzina
  • 1,470
  • 11
  • 17
2

You should add flex: 1; on the both #flex-item-1 and #flex-item-2 otherwise, the text or the content will affect the #flex-item-1 width...

Try removing text from the #flex-item-1, you will see that everything works as expected.

Leon Vuković
  • 489
  • 3
  • 16