In a flex container, when flex items wrap, they tend to take up the maximum allowed space, leading to discrepant widths between items on different rows. To address this, we can employ the following CSS tricks:
@mixin flex-wrap-fix($flex-basis, $max-viewport-width: 2000px) { flex-grow: 1; flex-basis: $flex-basis; max-width: 100%; $multiplier: 1; $current-width: 0px; @while $current-width < $max-viewport-width { $current-width: $current-width + $flex-basis; $multiplier: $multiplier + 1; @media(min-width: $flex-basis * $multiplier) { max-width: percentage(1/$multiplier); } } }
Apply the mixin to the flex item:
.flex-item { @include flex-wrap-fix(100px) }
@mixin flex-container-wrap-items($flex-basis, $max-expected-width: 2000px) { display: flex; flex-wrap: wrap; > * { max-width: 100%; flex-grow: 1; flex-basis: $flex-basis; } $multiplier: 1; $current-width: 0px; @while $current-width < $max-expected-width { $current-width: $current-width + $flex-basis; $multiplier: $multiplier + 1; &[min-width~="#{$flex-basis * $multiplier}"] > * { max-width: percentage(1/$multiplier); } } }
Apply the mixin to the flex container:
.flex-container { @include flex-container-wrap-items(100px) }
The above is the detailed content of How to Maintain Consistent Flex Item Widths Across Rows When Wrapping?. For more information, please follow other related articles on the PHP Chinese website!