Achieving Equal Width Columns in CSS Grid
When working with CSS Grid, distributing elements evenly across columns can be challenging. While Flexbox offers a straightforward approach, achieving the same result with CSS Grid requires a bit more consideration.
Original Question:
"I would like to display elements in a row in equal-width columns, regardless of the number of children within the row. I have tried using CSS Grid, but I'm having trouble making it work."
Answer:
The commonly suggested solution of repeat(3, 1fr) is not entirely accurate. As stated in the response:
"1fr is about the distribution of available(!) space. This breaks as soon as the content becomes bigger than the track size."
To ensure columns retain their equal width, it is recommended to utilize minmax(0, 1fr) instead:
<code class="css">grid-template-columns: repeat(3, minmax(0, 1fr));</code>
minmax(0, 1fr) permits grid tracks to be as small as 0 and as large as 1fr. This ensures that columns maintain equal widths. However, this approach may cause content overflow if it exceeds the column's width.
For a visual demonstration of the difference between these approaches, consider the following example:
<code class="html"><div class="row"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> </div></code>
With repeat(3, 1fr), the columns will adjust their widths based on the available space, potentially resulting in different widths. However, using repeat(3, minmax(0, 1fr)) will ensure that all three columns have exactly the same width, regardless of content size.
The above is the detailed content of How to Achieve Equal Width Columns in CSS Grid Regardless of Content Size?. For more information, please follow other related articles on the PHP Chinese website!