CSS Grid introduced a new measurement unit to the world. It’s actually a new type of flexible unit called Fr unit. The meaning of Fr is Fractional Unit, where 1fr represents a fraction of the available space.
Below you’ll find two examples of using the fr unit. Prior to that, It is vital to understand that the elements themselves (the grid items) in these examples are positioned on the grid using the grid areas property as follows:
.grid-wrap {
max-width: 100%;
margin: 3em auto;
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-template-rows: 50px 150px 50px;
grid-template-areas: "head head2 . side" "main main2 . side" "footer footer footer footer";
}
Each of the four columns occupies the same place in the grid.
Examples of Using fr
Here’s the same example as above with different fr values. Pay attention to the change in layout:
.grid-wrap {
/* ... */
grid-template-columns: 1fr 1fr 40px 20%;
grid-template-rows: 100px 200px 100px;
/ * ... */
}
In the next and last example, the sidebar covers 2fr of the space, so it will have the same width as the elements filling the first and second columns:
.grid-wrap {
/* ... */
grid-template-columns: 1fr 1fr 40px 2fr;
grid-template-rows: 100px 200px 100px;
/* ... */
}
Mixed Units
As you saw in the last two examples, you can mix values, meaning you can simultaneously use values of percentage, fixed, and fr types. The fr values will be distributed among the remaining space after the other values occupy the required place.
For example, if we have a grid with 4 columns like in the following snippet, the first column will be 300px, the second will be 80px (10% of 800), and the third and fourth columns will each be 210px, taking up half of the remaining space:
main {
width: 800px;
display: grid;
grid-template-columns: 300px 10% 1fr 1fr;
/* 300px 80px 210px 210px */
grid-template-rows: auto;
}
This post is completely translated from the following alligator.io post.
Hmm… seems to me there might be an error(s) on the page as the examples don’t seem to be displaying correctly at all, whereas the original post you referenced/translated from (re; alligator, which actually redirects to digitalocean) displays perfectly/as intended.
Lots of confusion here. ¯\_(ツ)_/¯
Hey Matt!
I appreciate you notifying me about the errors. It’s been fixed!
All the best 🙂
Beauty!
Cheers, Roee