Markdown

fr

fr is the Acronym for Fractional Unit

A flexible unit in CSS Grid that represents a fraction of the available space within a grid container. Unlike fixed units like pixels or percentages, the fractional unit (fr) dynamically distributes space based on the number of fractional units assigned to each column or row. This makes it an essential tool for creating fluid, adaptable grid layouts without relying on media queries.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

Origins of fr

The fractional unit was introduced with CSS Grid Layout to simplify dividing space within a container. Unlike older methods that relied on percentages or fixed widths, fr automatically adjusts to available space while maintaining proportional relationships between elements. This eliminates the need for manual calculations and ensures layouts remain responsive.

  • Example: Consider a 3-column grid:

“`css .container { display: grid; grid-template-columns: 1fr 1fr 1fr; } “` Each column receives an equal share of the available space, effectively creating a three-column layout without specifying pixel values.

Use Cases for fr

  • Creating Equal Columns Without Fixed Widths:

“`css .grid { display: grid; grid-template-columns: 1fr 1fr 1fr; } “` This creates three equal-width columns that expand and shrink based on the container size.

  • Proportional Distribution of Space:

“`css .grid { display: grid; grid-template-columns: 2fr 1fr; } “` The first column gets twice the space of the second, maintaining this ratio regardless of screen size.

  • Mixing fr With Fixed and Min/Max Units:

“`css .grid { display: grid; grid-template-columns: 200px 1fr 2fr; } “` This layout keeps the first column fixed at 200px, while the remaining space is distributed in a 1:2 ratio between the last two columns.

Difference Between fr and Other Units

  • fr vs. px: Pixels are fixed, while fractional units are flexible.
  • fr vs. %: Percentages divide space relative to the parent but can lead to inconsistent results when used with gaps and auto layouts.
  • fr vs. auto: The auto value lets an element grow based on its content, while fr distributes space based on the available container width.