Home > Web Front-end > CSS Tutorial > CSS Grid: Percentages vs. `fr` Units: Which Should I Use?

CSS Grid: Percentages vs. `fr` Units: Which Should I Use?

Barbara Streisand
Release: 2024-12-13 08:31:10
Original
778 people have browsed it

CSS Grid: Percentages vs. `fr` Units: Which Should I Use?

Percentage vs. Fr Units in CSS Grid Layout

Understanding fr Units

Function: Fr units allocate free space within a container.

Calculation: Free space (after subtracting grid gaps) is divided equally among the fr columns.

Understanding Percentage (%) Units

Function: Defines column widths as a percentage of the container's width.

Calculation: Column width is determined by dividing the total width by the number of columns, including the widths of any grid gaps.

The Difference: Overflow vs. Distribution

Percentage: Columns can overflow outside the container width due to fixed unit lengths and grid gaps.

Fr: Columns only take up free space within the container, not extending beyond it. Grid gaps do not impact free space allocation.

Using Percentage with Grid Gaps

To avoid overflow with percentage widths, subtract the total width of the grid gaps from the full container width before dividing by the number of columns:

grid-template-columns: repeat(12, calc(8.3333% - 9.1667px))
Copy after login

where:

  • 8.3333% is the percentage width of each column without gaps
  • 9.1667px is the total width of 11 grid gaps (10px each)

By using appropriate values for percentage widths or implementing fr units, you can manage column sizing and prevent overflow in CSS Grid Layout.

The above is the detailed content of CSS Grid: Percentages vs. `fr` Units: Which Should I Use?. 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