Flex in CSS: shrink to fit
The CSS flex-shrink
property lets you specify how much a flex item will shrink if there is not enough space for it to fit in the flex container:
/* Safari 6.1 and above */
a:nth-of-type(1) {
-webkit-flex-shrink: 2;
}
/* Standard syntax */
a:nth-of-type(1) {
flex-shrink: 2;
}
This property is a direct opposite of flex-grow. They are often used together, and you can also use the CSS flex shorthand for both of them.
The CSS flex-shrink syntax
flex-shrink
only requires specifying one value in a unitless number:
flex-shrink: value;
The default value for CSS flex-shrink
is 1
, which means the element cannot shrink further than the size required to fit its content. If you define 0
as the value, the flex item will not shrink at all. You cannot use negative values.
Just like flex-grow
, CSS flex-shrink
divides the space up among flex items according to the ratio defined by the specified values. The difference is that the space is negative in this case, which means the actual flex items shrink in size. If all the items have the same flex-shrink
value, they all lose the same portion of size.
Imagine we have three items in the same flex container. See what their flex-shrink values specify: |
||
---|---|---|
First item | flex-shrink: 1; |
Loses 1/6 of the space the container lacks to fit all the items |
Second item | flex-shrink: 3; |
Loses 3/6 (half) of the free space the container lacks to fit all the items |
Third item | flex-shrink: 2; |
Loses 2/6 (a third) of the free space the container lacks to fit all the items |