The FR unit — Fractional units in CSS grid

Fractions — or fractional units. FRs. These things are life-changing. Check this out the traditional way: We have four columns. Each set to 25% width. Making this parent grid a total of, spoiler
alert: 100%. Want to change any one of them? You’ll need calculus. Except you won’t, but it’s a pain. Why? If we make this one 50%, the others maintain
their original sizing. And three 25s and a 50 is no longer 100%. It’s 125%. Hence the overflow. And we know why this happens: the other three
are still taking up 25% of the parent, and the new one hasn’t subtracted from that at
all. It gets crazier. What if you’re mixing units? There are times where this happens. And following the math can be excruciating. Perhaps more importantly, it holds us back
from design. Enter: CSS fractional units. Or, as Tolstoy called them, FRs. FRs do all the heavy lifting inside anything
that’s a grid. Scalability? Check. No manual calculations? Check. And the math is super straightforward. It works like this: Same four columns. All even. Each are now 1 FR (one fractional unit). So any one of these four is 1/4th that width. Want one of them to be twice as wide? Make it 2 FR. Notice how the others resized. Now it didn’t do this randomly. They worked it out because the total is now
5 FRs. Now each of them take 1/5th while our new
one takes up 2/5ths. And notice how we can change our gap? No need to recalculate. Everything just works. But wait. It gets better. Think of the FR here (these fractional units)
as two things: A maximum, and a minimum. The maximum is whatever you set. In FRs. We already know how that works. But what’s the minimum? What happens if we have content in here like
a heading? The other columns will shrink proportionally. So with FRs, the minimum is automatic (or
auto). FR automatically sets minimums which will
respect the content inside. Now we can override this minimum. We can set a minimum which gives us control
over everything. With flexbox, this would require scratch paper,
a calculator, and a subscription to Netflix, because, as we know, layout troubles are the
third-leading cause of procrastination in web development. But that’s the FR unit. FRs let you enter whole numbers, decimals
— they’re all relative to each other. Set your columns and rows to anything you
want. And because this works like a fraction, you
can put all sorts of values in here. It all works out, regardless of any gap in
your grid. Fractions that just work. That’s the FR unit.


Add a Comment

Your email address will not be published. Required fields are marked *