MeNeedHelp
MeNeedHelp

Reputation: 55

flex vs flex-grow producing different results

Learning Flexbox & I don't understand why flex property is behaving the way it is. As I understand it, flex is simply shorthand for flex-grow, flex-shrink, and flex-basis with the last two being optional.

In my example below, I expected the same result using flex-grow vs flex with just the first value defined. I am getting different results but I don't understand why. The results in the first container is what I was expecting in both. Seems so straight forward I don't know what I am missing - shorthand properties don't work the way I am understanding them? Appreciate any help.

.container {
  height: 200px;
  width: 100%;
  background: lightgray;
  margin: 20px auto;
  display: flex;
  align-items: center;
}

.item {
  height: 50px;
  width: 300px;
  align-items: flex-end;
}

.item1 {
  border: 1px solid red;
  flex-grow: 0;
}

.item2 {
  border: 1px solid green;
  flex-grow: 1;
}

.item3 {
  border: 1px solid red;
  flex: 0;
}

.item4 {
  border: 1px solid green;
  flex: 1;
}
  <div class="container">
    <div class="item item1"></div>
    <div class="item item2"></div>
  </div>

  <div class="container">
    <div class="item item3"></div>
    <div class="item item4"></div>
  </div>

Upvotes: 1

Views: 364

Answers (2)

HijenHEK
HijenHEK

Reputation: 1296

using flex instead of the trio grow shrink and basis is little bit trickier than how it looks.. the second and third parameters are not optional , you can choose to use flex alone with one value two or 3 but it will behave differently depending on the value you pass

according to mdn : case of a unitless number as flex value

flex : <number>  ;
/*translates to :*/ 
flex : <number> 1 0 ;

in your case flex is set to 0 so you have :

flex : 0  ;
/*translates to :*/ 
flex : 0 1 0 ;

so flex-basis which is the last one is set to 0 and flex grow is 0 so its not the same as item1 . having no basis and shrink set to 1 , item 4 will take the whole row since he has grow of 1

for item 4 you have

flex : 1  ;
/*translates to :*/ 
flex : 1 1 0 ;

Upvotes: 0

Michael Benjamin
Michael Benjamin

Reputation: 371699

When you set only flex-grow, the flex-basis property remains unaffected. It still defaults to flex-basis: auto.

When you use the flex property, flex-basis gets reset to 0.

So flex: 0 is shorthand for flex-grow: 0 and flex-basis: 0. This means 0 width.

With flex-grow: 0 you still have flex-basis: auto.

To understand the difference between flex-basis: 0 and flex-basis: auto, see this post:

Upvotes: 1

Related Questions