Home > Web Front-end > CSS Tutorial > How to Create Equal-Width Columns with CSS Grid Regardless of Content Size?

How to Create Equal-Width Columns with CSS Grid Regardless of Content Size?

Barbara Streisand
Release: 2024-11-05 10:01:02
Original
539 people have browsed it

How to Create Equal-Width Columns with CSS Grid Regardless of Content Size?

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

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!

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