Code

CSS

CSS Grid

Two-dimensional layout — define rows and columns, then place items precisely or let the browser auto-place them. MDN Reference

1. grid-template-columns & rows

3 equal columns with fr

1
2
3
4
5
6

Mixed: fixed + fluid

sidebar
main
aside

repeat(4, 1fr)

A
B
C
D
.grid {
  display: grid;

  /* 3 equal columns */
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-columns: repeat(3, 1fr);

  /* Fixed sidebar + fluid main + aside */
  grid-template-columns: 200px 1fr 160px;

  /* 4 equal columns */
  grid-template-columns: repeat(4, 1fr);

  /* Named rows */
  grid-template-rows: auto 1fr auto;

  gap: 1rem;
}

2. Placing items — column & row span

span 2 cols
3
4
row span 2
6
7
/* Span shorthand */
.item {
  grid-column: span 2;
  grid-row:    span 2;
}

/* Explicit placement */
.item {
  grid-column: 1 / 3;  /* from line 1 to 3 */
  grid-row:    2 / 4;
}

/* Shorthand: row-start/col-start/row-end/col-end */
.item {
  grid-area: 2 / 1 / 4 / 3;
}

3. grid-template-areas

header
sidebar
main
.page {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header  header"
    "sidebar main"
    "footer  footer";
  gap: 0.5rem;
  min-height: 300px;
}

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

4. auto-fill & auto-fit with minmax()

auto-fill — keeps empty tracks

A
B
C

auto-fit — collapses empty tracks

A
B
C
/* Responsive grid — no media queries needed */
.grid {
  display: grid;
  gap: 1rem;

  /* auto-fill: preserves empty column tracks */
  grid-template-columns:
    repeat(auto-fill, minmax(150px, 1fr));

  /* auto-fit: stretches items to fill space */
  grid-template-columns:
    repeat(auto-fit, minmax(150px, 1fr));
}

5. Alignment — justify & align

justify-items: center + align-items: center

A
B
C

justify-content: space-between

X
Y
Z
/* Aligns content within each cell */
.grid {
  justify-items: start | center | end | stretch;
  align-items:   start | center | end | stretch;
}

/* Per item override */
.item {
  justify-self: center;
  align-self:   end;
}

/* Aligns the grid tracks in the container */
.grid {
  justify-content: space-between;
  align-content:   center;
}

/* Shorthand */
.grid {
  place-items:   center;   /* align justify */
  place-content: center;
  place-self:    end center;
}

6. grid-auto-flow: dense

span 2
2
3
span 2
5
6
7
/* Back-fills gaps left by spanning items */
.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-flow: dense;
  gap: 0.5rem;
}

/* Without dense: gaps appear */
/* With dense:    gaps filled */