Grid Columns, Rows & Fractional Units (fr)

Grid Columns, Rows & Fractional Units (fr) in CSS: While Flexbox is one-dimensional (operating on either a row OR a column), CSS Grid is a true two-dimensional…

While Flexbox is one-dimensional (operating on either a row OR a column), CSS Grid is a true two-dimensional layout engine that coordinates columns and rows simultaneously.


The Fractional Unit (fr)

The fr unit represents a fraction of the available free space in the grid container after all fixed units (px, rem) and gap gutters are deducted:

.dashboard-grid {
  display: grid;
  /* 250px fixed sidebar, main content takes 3 parts, right rail takes 1 part */
  grid-template-columns: 250px 3fr 1fr;
  grid-template-rows: auto 1fr auto;
  gap: 1.5rem;
  min-height: 100vh;
}

Line-Based Placement & Spanning

Every grid track is separated by numbered Grid Lines starting at index 1:

Line 1           Line 2           Line 3           Line 4
  |   Column 1     |   Column 2     |   Column 3     |

Child items can be positioned explicitly along grid lines:

.featured-article {
  /* Starts at Column Line 1, ends at Line 3 (spans 2 columns) */
  grid-column: 1 / 3;
  
  /* Or using the 'span' keyword: */
  grid-row: span 2;
}

/* Negative line numbers count from the end (-1 is the last line!) */
.full-width-banner {
  grid-column: 1 / -1; /* Spans across the entire grid from edge to edge! */
}

Named Grid Template Areas

For macro-page layouts, grid-template-areas provides a visual ASCII-art representation of the layout in your stylesheet:

.admin-shell {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr 50px;
  grid-template-areas:
    "header  header"
    "sidebar main"
    "sidebar footer";
  min-height: 100vh;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

Exercises

  1. Build an application layout with a header, 2-column body, and footer using grid-template-areas.
  2. Use negative grid line indexing (1 / -1) to make a hero section break out into full-bleed width.
  3. Compare the behavior of grid-template-columns: 1fr 1fr 1fr vs grid-template-columns: repeat(3, 1fr).