How to Use CSS to Allow Flex Items to Shrink

By Paul McFedries

Web designers often use CSS to allow flex items to shrink. The flexibility of flexbox means not only that flex items can grow to fill a flex container’s empty space, but also that they can shrink if the flex container doesn’t have enough space to fit the items. Shrinking flex items to fit inside their container is the default flexbox behavior, but you gain a measure of control over which items shrink and by how much by using the flex-shrink property on a flex item:

item {
 flex-shrink: value;
}

Here, value is a number greater than or equal to 0. The default value is 1, which tells the browser to shrink all the flex items equally to get them to fit inside the flex container.

For example, consider the following code:

CSS:

.container {
  display: flex;
  width: 500px;
  border: 5px double black;
}
.item {
  width: 200px;
}

HTML:

<div class="container">
  <div class="item item1">1</div>
  <div class="item item2">2</div>
  <div class="item item3">3</div>
  <div class="item item4">4</div>
  <div class="item item5">5</div>
</div>

The flex container (the container class) is 500px wide, but each flex item (the item class) is 200px wide. To get everything the fit, the browser shrinks each item equally.

The browser only shrinks each flex item truly equally (that is, by the same amount) when each item has the same size along the primary axis (for example, the same width when the primary axis is horizontal). If the flex items have different sizes, the browser shrinks each item roughly in proportion to its size: Larger items shrink more, whereas smaller items shrink less. The word “roughly” is used here because in fact the calculations the browser uses to determine the shrinkage factor are brain-numbingly complex. If you want to learn more, see MadebyMike.com.

For positive values of flex-shrink, you have three ways to control the shrinkage of a flex item:

  • Assign the item a flex-shrink value between 0 and 1. The browser shrinks the item less than the other flex items. For example, here’s a rule that sets flex-shrink to .5 for the element with class item1:
.item1 {
  flex-shrink: .5;
}
  • Assign the item a flex-shrink value greater than 1. The browser shrinks the item more than the other flex items. For example, the following rule sets flex-shrink to 2 for the element with class item1:
.item1 {
  flex-shrink: 2;
}
  • Assign the item a flex-shrink value of 0. The browser doesn’t shrink the item. The following rule sets flex-shrink to 0 for the element with class item1:
.item1 {
  flex-shrink: 0;
}

If a flex item is larger along the primary axis than its flex container, and you set flex-shrink: 0 on that item, ugliness ensues. That is, the flex item breaks out of the container and, depending on where it sits within the container, might take one or more other items with it. If you don’t want a flex item to shrink, make sure the flex container is large enough to hold it.