Creating Equal-Width Columns with CSS Grid
You want to display children within a row element in an equal number of columns, regardless of the number of children. While Flexbox can easily accomplish this, CSS Grid presents a different challenge. This article provides a solution to achieve this using CSS Grid.
Solution
The first common attempt is to use repeat(3, 1fr) as the value for the grid-template-columns property. However, 1fr calculates space distribution based on available space. This limitation is problematic when content exceeds the track size, preventing columns from overflowing and adjusting their widths accordingly. Partial columns with truncated content can become unequal.
To ensure exact equality in column width, you should use the following rule:
<code class="css">grid-template-columns: repeat(3, minmax(0, 1fr));</code>
minmax(0, 1fr) specifies that grid tracks can have a minimum size of 0 and an arbitrary maximum size of 1fr. This ensures that the columns will always be the same width and accommodate content that exceeds the track size.
Keep in mind that enabling content overflow can lead to different visual outcomes depending on the browser's default behavior, content size, or available space. The example provided in the question illustrates the difference between the two approaches: repeat(3, 1fr) versus repeat(3, minmax(0, 1fr)).
The above is the detailed content of How to Create Equal-Width Columns with CSS Grid Regardless of Content Size?. For more information, please follow other related articles on the PHP Chinese website!