0
0
CssConceptBeginner · 3 min read

What is the fr Unit in CSS: Explained with Examples

The fr unit in CSS stands for "fraction" and is used in CSS Grid layouts to allocate a portion of available space. It divides the container's free space into fractions, making it easy to create flexible and responsive grid columns or rows.
⚙️

How It Works

Imagine you have a pizza sliced into pieces. The fr unit is like saying, "Give me this many slices of the leftover pizza." It doesn’t count the pizza’s total size but divides the remaining space after fixed sizes are taken out.

In CSS Grid, when you set columns or rows using fr, the browser looks at the total space available, subtracts any fixed widths or gaps, then splits the leftover space into fractions. Each fr unit gets one part of that leftover space.

This makes layouts flexible because if the container grows or shrinks, the fractional parts adjust automatically, keeping the proportions consistent.

💻

Example

This example shows a grid with three columns. The first column takes 1 fraction, the second 2 fractions, and the third 1 fraction of the leftover 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: 5px;
}
Output
<div class="container"> <div class="box">1fr</div> <div class="box">2fr</div> <div class="box">1fr</div> </div>
🎯

When to Use

Use the fr unit when you want parts of your layout to share leftover space proportionally. It is perfect for responsive designs where fixed pixel widths don’t work well.

For example, if you want a sidebar and main content area where the main content is twice as wide as the sidebar, you can use grid-template-columns: 1fr 2fr;. This keeps the layout balanced even if the screen size changes.

It’s also great for creating equal-width columns or rows without calculating exact pixel sizes.

Key Points

  • fr stands for fraction of leftover space in CSS Grid.
  • It helps create flexible, responsive layouts without fixed widths.
  • Multiple fr units share space proportionally.
  • It only works inside CSS Grid containers.
  • Combines well with fixed units like px or em for mixed layouts.

Key Takeaways

The fr unit divides leftover space in CSS Grid into flexible fractions.
Use fr to create responsive columns or rows that adjust with container size.
Multiple fr units share space proportionally based on their values.
fr units only work inside CSS Grid layouts, not in other CSS contexts.
Combine fr with fixed units for precise and flexible grid designs.