DEV Community

Rae Liu
Rae Liu

Posted on • Edited on

CSS flexbox: how to use flex-shrink and flex-grow for responsive layout

It took me a while to figure out flexbox, espcially flex-shrink and flex-grow.
Here is a cheat sheet that I made based on developing experience, and I hope it will help you.

Responsive for all elements

Clean and easy -

.parent{

  display: flex;
}

.child{
  flex: 1 1 PERCENTAGE;
}
Enter fullscreen mode Exit fullscreen mode

All elements have fixed width

This can be used on carousel slideshow.

.parent{
  display: flex;
  flex-wrap: nowrap;
}
.fixed-elements{
  flex: 0 0 FIX_WIDTH;
}
Enter fullscreen mode Exit fullscreen mode

Note
If you set code as flex: 1 1 FIX_WIDTH, and then expect fixed width elements...
It won't happen. flex-basis has lower priority than flex-grow and flex-shrink. Flexbox is going to try any possibilities to make responsive layout🤷‍♀️.

Fixed width on one element, others are still responsive

.parent{
  display: flex;
  flex-wrap: nowrap;
}
.fixed-element{
  flex: 0 0 FIX_WIDTH;
}
.other-elements{
  flex: 1 1 PERCENTAGE;
}
Enter fullscreen mode Exit fullscreen mode

What does those numbers mean

Let's talk about what exact those numbers mean on flex-shrink and flex-grow.
They are all relative numbers, which means it will depend on their siblings.

flex-grow
0 - The element will give up the chance to grow if there is space available.
1 - The element will grow if there is space available.
2 or more - The element will look for other siblings flex-grow's value, and do the math.
for example, if div_1 ==1, div_2==2, then div_1 is 1/3 of the width, and div_2 is 2/3.

flex-shrink
0 - The element will give up the chance to shrink, and the content won't be wrapped either.
1 - The element will shrink if there is not enough space
2 or more - same as flex-grow, the element will sum up all siblings' flex-shrink value, and do the math.

Note
The default number in IE11 is 0 while other browsers are 1. So make sure to reset the number to 1 if your code needs to be shown on IE...

Examples

Top comments (0)