In this article I am going to answer below questions about fr units:
- What is fr units and how it works?
- What is the difference in using percentage and fr units inside grid container?
- Will fr units works outside grid container?
- What is the browser support?
- How it behaves in different screen sizes?
Let’s us answer these questions one by one.
What is fr units and how it works?
CSS Grid layout module is shipped with a new css unit called
frunit. fr stands for “fraction”. Fraction is a proportion of available space.Let’s understand this better with example.
Example: We have a box of width and height 300x150px and if we divide it into 3 parts of 2fr, 1fr and 1fr respectively. then first part of my box will be twice of the other parts. First item became 150px and other two items became 75px each. Let’s see how fr calculates the width of each item.
Total fr = 2fr + 1fr + 1fr = 4frItem 1 = 2fr/4fr* 300px = 150pxItem 2 = 1fr/4fr*300px = 75pxItem 3 = 1fr/4fr*300px = 75px
frunit accepts not only “Whole numbers” but “decimal numbers” as well.
What is the difference in using percentage and fr units inside grid container?
We will understand this by taking the above example with grid-gap: 20px for both the cases percentage as well as fr.
Fr units calculates based on available space. First it will deduct the grid gap from total width and then calculate the proportion.
grid-template-columns: 2fr 1fr 1fr; grid-gap: 20px;
New width = 300-2*20 = 260pxItem 1 = 2fr/4fr*260px = 130px
Item 2 = 1fr/4fr*260px = 65px
Item 3 = 1fr/4fr*260px = 65px
Percentages are length units and not the flex unit. Width of the column is calculated based on the container width without taking into account any grid-gaps. The addition of grid-gaps will push the content outside the container. As shown below:
grid-template-columns: 50% 25% 25%;
To avoid this we need to deduct the size of grid-gap from the columns. So use calc() to define the width of the columns.
Here there are two grid-gaps, We will deduct it from last two columns:
grid-template-columns: 50% calc(25%-20px) calc(25%-20px); grid-gap: 20px;
Item 1 = 50%; = 150px Item 2 = calc(25% - 20px) = 55pxItem 3 = calc(25% - 20px) = 55px
Will fr units works outside grid container?
Fr units cannot be used outside the grid container. It will be effective only to the direct children of the grid container.
What is the Browser support?
It supports all modern browsers, if you want to know in detail about this check out below link:
You can check here — https://caniuse.com/#feat=css-grid
How it behaves in different screen sizes?
It will behave exactly same for all the screen sizes because it works based on the available space.