Firefox DevTools

Introduction to CSS Grid Layout

Launch Video Playerplay icon

The fr Unit

In our first grid, we created columns with a fixed px width. That's great, but it isn't very flexible. Thankfully, CSS Grid Layout introduces a new unit of length called fr, which is short for “fraction”. MDN defines the fr unit as a unit which represents a fraction of the available space in the grid container. If we want to rewrite our previous grid to have three equal-width columns, we could change our CSS to use the fr unit:


.container {
  display: grid;
  width: 800px;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 150px 150px;
  grid-gap: 1rem;
}
      

The repeat() notation

Handy tip: If you find yourself repeating length units, use the CSS repeat() function. Rewrite the above code like so:

      
.container {
  display: grid;
  width: 800px;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 150px);
  grid-gap: 1rem;
}
      

Here is the result:

View on Codepen

Firefox DevTools + CSS Grid Layout

Inspect the above grid and change the grid-template-columns property on the grid container to the following:


grid-template-columns: 10px repeat(2, 1fr);
      

What happened? As you can see, you can not only use the repeat() notation for just part of the track listing, but you can also mix units (in this case, px and fr).

We will learn more about mixing units in the next section.

Get the browser with the best tools for Developers