Home > Web Front-end > CSS Tutorial > How Can I Achieve Equal Width Flex Items Across Rows, Even When Wrapping?

How Can I Achieve Equal Width Flex Items Across Rows, Even When Wrapping?

Mary-Kate Olsen
Release: 2024-12-19 16:42:10
Original
393 people have browsed it

How Can I Achieve Equal Width Flex Items Across Rows, Even When Wrapping?

Equal Width Flex Items in Variable-Sized Containers

Flexbox allows for flexible and responsive layouts, but it can encounter challenges when attempting to maintain equal width among flex items after the list wraps.

Current Flexbox Limitations

In its current specification, Flexbox lacks a native solution for equal width alignment on the last row. This is due to the fact that flex items are sized based on available space, and the last row may have less space remaining.

Alternative Solution: Grid Layout

Grid Layout, another CSS layout technique, offers a more robust solution for this alignment issue. Grids allow for explicit sizing and positioning of elements within a container:

CSS Code

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-auto-rows: 20px;
  grid-gap: 5px;
}

.item {
  background: yellow;
  text-align: center;
  border: 1px solid red;
}
Copy after login

Explanation

  • The grid-template-columns property defines the size and number of columns in the grid (as many as fit the container, each with a minimum width of 100px and a flexible 1fr unit).
  • The grid-auto-rows property sets the height of the rows (20px in this case).
  • grid-gap specifies the space between items.

This configuration effectively distributes the available width equally among the flex items, allowing them to wrap and maintain their equal size even on the last row.

The above is the detailed content of How Can I Achieve Equal Width Flex Items Across Rows, Even When Wrapping?. 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