Skip to main content

CSS Grid

12th October, 2022

Updated: 12th October, 2022

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

    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:

    When declaring track sizes, you can use fixed sizes with units such as px and em. You can also use flexible sizes such as percentages or the fr unit. The real magic of CSS Grid Layout, however, is the ability to mix these units. The best way to understand is with an example:

    .container {
      width: 100%;
      display: grid;
      grid-template-columns: 100px 30% 1fr;
      grid-template-rows: 200px 100px;
      grid-gap: 1rem;
    }
        
          

    Here, we have declared a grid with three columns. The first column is a fixed width of 100px. The second column will occupy 30% of the available space, and the third column is 1fr which means it will take up a fraction of the available space. In this case, it will take up all of the remaining space (1/1).

    Here is our HTML:

    <div class="container">
      <div class="item" />
      <div class="item" />
      <div class="item" />
      <div class="item" />
      <div class="item" />
      <div class="item" />
    </div>
          

    Grid position

    Say we want to position our first grid item (with a class of item1) to be in the second row and occupy the second column. This item will need to start at the second row line, and span to the third row line. It will also need to start at the second column line and span to the third column line. We could write our CSS like so:

    .item1 {
      grid-row-start: 2;
      grid-row-end: 3;
      grid-column-start: 2;
      grid-column-end: 3;
    }
          

    Shorthand property

    We can also rewrite this with shorthand properties:

    .item1 {
      grid-row: 2 / 3;
      grid-column: 2 / 3;
    }
          

    47c5cba5-198f-4fe5-8080-cf800df348b5

    Created on: 12th October, 2022

    Last updated: 12th October, 2022

    Tagged With: