Flex Items Disregarding Margins and Border-Box Sizing
In flexbox, by setting flex: 1 1 33.33% and margin: 10px on flex items, one might expect three boxes per row. However, with flex-wrap: wrap, the boxes do not shrink to fit three per row.
The reason lies in the nature of box-sizing: border-box. While this property includes padding and borders in the width and height calculations, it excludes margins. Margins are calculated separately, and by default, flex items have flex-shrink: 1, allowing them to shrink in order to fit the container.
To resolve this issue, one can override the default behavior by setting flex-shrink: 0. This prevents the flex items from shrinking into the margins.
Another solution is to adjust the flex-basis value while keeping flex-grow: 1. Since there is no need for flex-basis to enforce a wrap due to flex-grow consumption of free space, one can reduce the value to accommodate the margins. By setting flex: 1 1 26% and margin: 10px, for example, the flex items now fit as expected.
The above is the detailed content of Why Don\'t Flex Items Shrink to Fit Three Per Row with Margins and `border-box` Sizing?. For more information, please follow other related articles on the PHP Chinese website!