Home > Web Front-end > CSS Tutorial > What's the Key Difference Between `fr` and Percentage Units in CSS Grid Layout for Column Widths?

What's the Key Difference Between `fr` and Percentage Units in CSS Grid Layout for Column Widths?

Susan Sarandon
Release: 2024-12-10 05:10:14
Original
189 people have browsed it

What's the Key Difference Between `fr` and Percentage Units in CSS Grid Layout for Column Widths?

The Difference Between Percentage and fr Units in CSS Grid Layout

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

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

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!

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