0
0
CssConceptBeginner · 3 min read

What is fr in CSS Grid: Understanding the Fraction Unit

In CSS Grid, fr stands for "fraction" and represents a portion of the available space in the grid container. It lets you divide space into flexible parts, so columns or rows grow or shrink proportionally based on the total free space.
⚙️

How It Works

Imagine you have a pizza and want to share it fairly among friends. The fr unit in CSS Grid works like slicing that pizza into parts. Each fr is a slice representing a fraction of the leftover space after fixed sizes are taken.

For example, if you set two columns with 1fr and 2fr, the first column gets one slice and the second gets two slices of the remaining space. This makes layouts flexible and easy to adjust without hard coding pixel sizes.

This unit only divides the space left after accounting for fixed widths, margins, and gaps, so it adapts smoothly to different screen sizes.

💻

Example

This example shows a grid with three columns using fr units. The first column takes 1 part, the second 2 parts, and the third 1 part of the available space.

css
html, body {
  height: 100%;
  margin: 0;
  font-family: Arial, sans-serif;
}
.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 10px;
  height: 100vh;
  padding: 10px;
  background-color: #f0f0f0;
}
.box {
  background-color: #4a90e2;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  border-radius: 8px;
}
Output
<div class="container"> <div class="box">1fr</div> <div class="box">2fr</div> <div class="box">1fr</div> </div>
🎯

When to Use

Use fr units when you want your grid columns or rows to share space proportionally and adapt to different screen sizes. It is perfect for responsive layouts where fixed pixel sizes would be too rigid.

For example, use fr to create a sidebar and main content area where the main content should take more space but both adjust fluidly as the window resizes.

It also works well for equal-width columns or any layout where you want to divide leftover space without calculating exact pixel values.

Key Points

  • fr means fraction of leftover space in a grid container.
  • It creates flexible, proportional columns or rows.
  • Only divides space after fixed sizes and gaps are accounted for.
  • Great for responsive and adaptable layouts.
  • Easy to use instead of fixed pixel widths.

Key Takeaways

fr is a flexible unit representing a fraction of available space in CSS Grid.
It helps create responsive layouts by dividing leftover space proportionally.
Use fr instead of fixed widths for adaptable columns or rows.
The total fr units share only the space left after fixed sizes and gaps.
Ideal for layouts that need to adjust smoothly on different screen sizes.