Home >Web Front-end >CSS Tutorial >How Can I Achieve Equal-Width Flex Items Even After They Wrap?

How Can I Achieve Equal-Width Flex Items Even After They Wrap?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 07:35:44467browse

How Can I Achieve Equal-Width Flex Items Even After They Wrap?

Equal Width Flex Items Even After They Wrap

In the domain of CSS positioning, achieving equal widths for flex items even after they wrap can present a challenge. Flexbox, a powerful layout module, falls short of providing a native solution for this scenario.

Current flexbox implementations lack the ability to align flexible items evenly in the last row or column. This limitation is inherent to the current specification and remains unresolved.

For more in-depth analysis and alternative approaches to addressing this issue, refer to these relevant resources:

  • [Sizing flex items on the last row](https://stackoverflow.com/questions/34259120/sizing-flex-items-on-the-last-row)
  • [Is it possible for flex items to align tightly to the items above them?](https://css-tricks.com/flexbox-tightly-align-last-row/)

However, outside of flexbox, CSS Grid Layout offers a straightforward solution to this problem:

.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;
}
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
  <div class="item">9</div>
  <div class="item">10</div>
</div>

With this CSS Grid solution, you can effortlessly align flexible items with equal widths, even when they wrap onto multiple lines.

The above is the detailed content of How Can I Achieve Equal-Width Flex Items Even After They Wrap?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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