Search

CSS Grid Fr Unit Explained

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, I’ll present two examples of using the fr unit. Before that, note 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.

Head
Head 2
Main
Main 2
Side
Footer

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;

    / * ... */
}
Head
Head 2
Main
Main 2
Side
Footer

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;
  
    /* ... */
}
Head
Head 2
Main
Main 2
Side
Footer

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.

Roee Yossef
Roee Yossef

I develop websites & custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

3 Comments...
  • Matt 13 March 2024, 16:50

    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. ¯\_(ツ)_/¯

    • רועי יוסף 14 March 2024, 0:16

      Hey Matt!

      I appreciate you notifying me about the errors. It’s been fixed!

      All the best 🙂

      • Matt Rock 14 March 2024, 15:15

        Beauty!

        Cheers, Roee

Leave a Comment

Up!
Blog