In flexbox layouts, maintaining a consistent item width across multiple lines can be challenging. However, this can be achieved through a combination of CSS properties, as described below:
Sets the factor by which an item grows relative to other items. By setting this to 1, each item has equal growth potential.
Defines the initial size of an item. This determines the minimum width of the item.
Sets the maximum width of an item, ensuring it doesn't exceed its desired size.
Media queries are used to adjust the max-width property based on viewport size, maintaining item width consistency across multiple lines.
ul { display: flex; flex-wrap: wrap; } li { max-width: 100px; flex: 1 0 0; } @media (min-width: 200px) { li { max-width: 50%; } } @media (min-width: 300px) { li { max-width: 33.33333%; } }
This CSS sets the initial width of each item to 100px. It then uses media queries to adjust the max-width property as the viewport size changes, ensuring that the items maintain their desired width even when they wrap to a new line.
A more elegant alternative is to utilize the flex-wrap-fix mixin:
@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) }
This mixin achieves the same result as the CSS media queries but eliminates the need for repetitive code and makes maintenance easier.
The above is the detailed content of How to Maintain Consistent Item Width in Flexbox Layouts After Wrapping?. For more information, please follow other related articles on the PHP Chinese website!