flex-shrink
property on a flex item:
<em>item</em> { flex-shrink: <em>value</em>; }Here,
<em>value</em>
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 offlex-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 setsflex-shrink
to.5
for the element with classitem1
:
.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 setsflex-shrink
to2
for the element with classitem1
:
.item1 { flex-shrink: 2; }
- Assign the item a
flex-shrink
value of 0. The browser doesn't shrink the item. The following rule setsflex-shrink
to0
for the element with classitem1
:
.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.