Limpuls Limpuls - 1 month ago 5
CSS Question

Flexbox grow and shrink property columns vs determined width columns for responsive grid system

Lately I've been learning flexbox and how to make my own grid system. When making grid system using floats, we determine number of columns per layout and each column's width in percentages. But when using flexbox, all the layout tutorials I saw are simply using

flex-direction: row;
and
flex: 1

for columns, to make all of them equal size, equal gutter, centered and in one row. But when I checked flexboxgrid source code on github, they are using same principle as bootstrap 3. They have columns for different screen sizes, 12 columns and
flex-grow
,
shrink
are disabled. Instead, each column is determined in width percentages, like
col-xs-1
max-width: 8.33%
.

Now I'm wondering what's the difference between these two techniques and which one is more preferable. I mean determining width for each column requires a lot of counting, while using flex grow property just fulfills the whole viewport in main axis with equally sized columns and gutters.

Answer

tl;dr

They are not techniques to achieve the same result, they do different things.


Flexbox grid uses flex-basis to determine the width in the flexbox container's main axis. It does not use flex: 1; on flex items because that is equivalent to flex: 1 1 0;. Which means flex-basis would have a value of 0, and the flex items sizes will be proportional to the specified grow and shrink factor.


Example

col-xs-1 with a flex-basis of 0 specified from flex: 1; would grow as if it was col-xs-12 if it is the only child, if there is another col-xs-1 like this as a sibling, then it would grow as if it was col-xs-6 and so forth.

It is expected for every col-xs-1 to fill 10% of the container, which would not be the case using flex: 1;.

* {
  box-sizing: border-box;
}
article {
  margin-bottom: 1rem;
}
[class^="col-"],
[class*="col-"] {
  flex: 0 0 auto; /* flex-grow: 0; flex-shrink: 0; flex-basis: auto; */
}
.row {
  display: flex;
  margin-right: -.5rem;
  margin-left: -.5rem;
}
.col-xs-1 {
  padding-right: .5rem;
  padding-left: .5rem;
  flex-basis: 8.33333333%;
}
.box-row {
  min-height: 1em;
  background: #007FFF;
}
article:last-of-type .col-xs-1 {
  flex: 1;  /* Same as flex: 1 0 auto; */
}
<article class="row">
  <section class="col-xs-1">
    <div class="box-row"></div>
  </section>
  <section class="col-xs-1">
    <div class="box-row"></div>
  </section>
</article>

<article class="row">
  <section class="col-xs-1">
    <div class="box-row"></div>
  </section>
  <section class="col-xs-1">
    <div class="box-row"></div>
  </section>
</article>