CS CSS

CSS: Grid Layout

What you will learn

CSS Grid creates two-dimensional layouts — rows and columns simultaneously. Use it for page-level layouts where flexbox becomes awkward.

Basic grid

.grid {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;  /* three equal columns */
    gap: 20px;                           /* spacing between cells */
}

Grid properties

On the container

Property What it does Example
grid-template-columns Define column sizes 1fr 1fr, repeat(3, 1fr), 200px auto
grid-template-rows Define row sizes 100px auto 100px
gap / row-gap / column-gap Spacing 20px
grid-template-areas Named layout sections See below
justify-items Horizontal alignment within cells center, stretch
align-items Vertical alignment within cells center, stretch

On the items

Property What it does
grid-column Span multiple columns: 1 / 3 or span 2
grid-row Span multiple rows
grid-area Place in a named area (grid-template-areas)

Named grid areas (page layout)

.page {
    display: grid;
    grid-template-areas:
        "header  header"
        "sidebar main"
        "footer  footer";
    grid-template-columns: 200px 1fr;
    grid-template-rows: auto 1fr auto;
    min-height: 100vh;
}
header { grid-area: header; }
aside  { grid-area: sidebar; }
main   { grid-area: main; }
footer { grid-area: footer; }

Grid vs Flexbox — when to use what

Use Case Best Choice
One-dimensional row or column (navigation bar, button row) Flexbox
Two-dimensional layout (page skeleton, card grid) Grid
Centering a single element Both work; flexbox is simpler
Content-driven layout where items wrap Flexbox with flex-wrap
Deliberate col/row alignment across tracks Grid

The fr unit

A fraction (fr) distributes available space proportionally. 1fr 1fr 1fr = three equal columns. 2fr 1fr = the first column gets twice as much space as the second.

Common mistakes

  • Using Grid where flexbox would suffice (one-dimensional layout).
  • Forgetting that 1fr distributes remaining space after fixed-width columns.
  • Not specifying grid-template-columns — the grid falls back to auto which behaves like a single column.
  • Confusing justify-items (aligns within cells) with justify-content (aligns the entire grid within the container).

Quick check below!