Lesson 33 +10 XP

Grid Items & Areas

Grid items & Template Areas

Place items EXACTLY where you want them!

Line-based placement

Grid lines are numbered starting at 1. Place items by line:

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

Shortcut with span:

.item {
  grid-column: span 2;   /* cover 2 columns */
}

grid-area shorthand

grid-row-start / grid-column-start / grid-row-end / grid-column-end:

.item {
  grid-area: 1 / 1 / 3 / 3;   /* row1 ->3, col1 ->3 */
}

Named grid areas (very friendly!)

Define areas in the container, then assign items by name:

.grid {
  display: grid;
  grid-template-columns: 1fr 3fr;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  gap: 10px;
}
.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

justify-self / align-self

Per-item override inside the grid cell (stretch, start, center, end).

Center an item

.item {
  justify-self: center;
  align-self: center;
}

TL;DR

  • grid-column: start / end places items by line numbers.
  • span covers a number of cells.
  • grid-area = grid layouts with named areas.
  • justify-self/align-self tweak one item.