Home > Web Front-end > CSS Tutorial > How Can I Achieve Equal Width Flex Items Across Multiple Rows?

How Can I Achieve Equal Width Flex Items Across Multiple Rows?

Linda Hamilton
Release: 2024-12-27 17:06:11
Original
945 people have browsed it

How Can I Achieve Equal Width Flex Items Across Multiple Rows?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template