CSS flex-shrink property
The flex-shrink
property is a part of CSS Flexbox, which is a layout model used to arrange items within a container along a single axis. The flex-shrink
property determines how a flex item should shrink relative to other items in the flex container when there is not enough space available along the main axis.
The syntax for flex-shrink
is:
flex-shrink: <number>;
The <number>
value represents the flex shrink factor, and it determines how much the flex item will shrink in proportion to other items in the container. The default value is 1
, which means all flex items will shrink equally to fit the available space. If a flex item has a flex-shrink
value of 0
, it won’t shrink at all when there is not enough space.
Here’s how flex-shrink
works:
- Calculate the total amount of space needed by all the flex items without considering the
flex-shrink
property. - If there is extra space available after Step 1, distribute it among the flex items according to their
flex-grow
values (if any). - If there is not enough space after Step 1, reduce the size of flex items proportionally based on their
flex-shrink
values.
Let’s consider an example:
HTML:
<div class="flex-container">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
</div>
CSS:
.flex-container {
display: flex;
}
.flex-item {
flex-shrink: 1;
/* Additional properties like flex-grow, flex-basis, and flex are typically used for more advanced layout scenarios */
}
In this example, all flex items have flex-shrink: 1
, which means they will all shrink proportionally if there is not enough space to accommodate them. If, for example, there’s not enough space to fit all items on one line, they will be compressed based on their flex-shrink
values to maintain the overall layout.
Remember that flex-shrink
only comes into play when there’s insufficient space along the main axis, and it won’t have any effect if there’s enough space to accommodate all flex items without any shrinking.