Maintaining Equal Width Flex Items During Wrapping
In CSS, achieving a layout where flex items maintain equal width, even after wrapping to new lines, can be challenging.
Using Flexbox
With flexbox, while it is possible to configure items to dynamically grow to fill the container's width, there is no built-in feature to ensure equal width for all items, especially in the last row. This limitation stems from the current scope of the flexbox specification.
Alternative Approach: Grid Layout
Grid Layout, another CSS3 technology, provides a more flexible solution for last-row alignment. By utilizing the grid-template-columns property, it is possible to distribute items evenly, even when they wrap to multiple lines.
Implementation
To achieve the desired layout:
.container { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); grid-auto-rows: 20px; grid-gap: 5px; }
This code creates a grid with automatic column distribution based on the available width. Each column can contain one or more flex items with a minimum width of 100px and a flexible width that grows to fill the remaining space in the column. The grid-auto-rows property sets the height of each row to 20px, and grid-gap adds 5px of spacing between items.
Conclusion
While flexbox is a powerful layout tool, its current limitations make equal width alignment in the last row challenging. Grid Layout, with its more advanced capabilities, provides a reliable solution for this scenario.
The above is the detailed content of How Can I Achieve Equal Width Flex Items Across Multiple Rows?. For more information, please follow other related articles on the PHP Chinese website!