When using CSS Grid Layout, it's important to understand the difference between percentage and fr units in defining the width of columns.
fr Units
The fr unit represents "fractional unit," and it works only with the free space available in the container. When using fr units, the browser calculates the width of each column based on the remaining space after taking into account the grid gaps.
For example, in the code below, the grid container is divided into 12 columns, each taking up equal free space within the container:
grid-template-columns: repeat(12, 1fr);
Percentage Units
Percentage units, on the other hand, define the width of each column as a percentage of the total container width. This means that the width of each column is calculated based on the actual width of the container.
For example, in the code below, each column has a width of 8.33333%, which is 100% divided by 12:
grid-template-columns: repeat(12, calc(100% / 12));
Why Percentages Cause Columns to Overflow
The key difference between fr and percentage units is how they handle grid gaps. With fr units, grid gaps are subtracted from the container's free space before the column widths are calculated. This ensures that columns don't overflow the container's width.
However, with percentage units, grid gaps are added to the column widths. This means that even though the total width of the columns may be equal to 100%, the addition of grid gaps can cause the columns to overflow the container's width.
To resolve this issue, you can either use fr units or adjust the percentage calculations to account for grid gaps.
The above is the detailed content of What's the Key Difference Between `fr` and Percentage Units in CSS Grid Layout for Column Widths?. For more information, please follow other related articles on the PHP Chinese website!