How to Use fr Unit in CSS Grid for Flexible Layouts
fr unit in CSS Grid represents a fraction of the available space in the grid container. Use it in grid-template-columns or grid-template-rows to divide space proportionally among grid tracks, making layouts flexible and responsive.Syntax
The fr unit is used inside grid-template-columns or grid-template-rows to define flexible grid tracks. For example, grid-template-columns: 1fr 2fr; means the first column takes one part of the space, and the second column takes two parts.
1fr: One fraction of the available space.2fr: Two fractions of the available space.- Fractions share leftover space after fixed sizes (like pixels or percentages) are allocated.
grid-template-columns: 1fr 2fr 1fr;
Example
This example creates a grid with three columns where the middle column is twice as wide as the others. The grid container fills the width of the page, and the columns adjust their size proportionally.
html, body {
margin: 0;
height: 100%;
}
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
height: 100vh;
gap: 10px;
background-color: #f0f0f0;
padding: 10px;
}
.box {
background-color: #4a90e2;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
border-radius: 5px;
}Common Pitfalls
One common mistake is mixing fr units with fixed sizes without understanding how leftover space is calculated. Fixed sizes (like 100px) are taken out first, then the remaining space is divided by fr units. Another pitfall is using fr units inside grid containers without a defined size, which can cause unexpected results.
Also, avoid using fr units for content that needs a minimum size, as fr only distributes leftover space and does not guarantee minimum widths.
/* Wrong: No container width set, fr units may collapse */ .container { display: grid; grid-template-columns: 1fr 1fr; } /* Right: Container width set, fr units distribute space properly */ .container { display: grid; grid-template-columns: 1fr 1fr; width: 100%; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| grid-template-columns | Defines columns with fractions of space | grid-template-columns: 1fr 3fr 1fr; |
| grid-template-rows | Defines rows with fractions of space | grid-template-rows: 2fr 1fr; |
| fr unit | Fraction of leftover space after fixed sizes | 1fr means one part of available space |
| Mixing units | Fixed sizes allocated first, then fr units | 100px 2fr 1fr |
Key Takeaways
fr units in grid-template-columns or grid-template-rows to create flexible grid tracks.fr units divide leftover space proportionally after fixed sizes are allocated.fr units work as expected.fr units for minimum content sizes.fr with fixed units carefully to control layout precisely.