CSS Grid Layout

🎨 CSS Layout Lesson 9 Intermediate

CSS Grid is a two-dimensional layout system — it handles both rows and columns simultaneously. While Flexbox excels at component-level layout, Grid shines for full page layouts.

1 Defining a Grid
CSS — Grid Container
.layout {
  display: grid;

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

  /* Sidebar + main + sidebar */
  grid-template-columns: 240px 1fr 240px;

  /* Auto-fill responsive columns */
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));

  grid-template-rows: auto;
  gap: 24px;              /* row-gap and column-gap */
  column-gap: 32px;
  row-gap: 16px;
}
2 Placing Items
CSS — Grid Item Placement
.item {
  grid-column: 1 / 3;   /* start at line 1, end at line 3 (spans 2 cols) */
  grid-row: 2 / 4;       /* spans 2 rows */
}

/* Named template areas */
.page {
  display: grid;
  grid-template-areas:
    "header  header"
    "sidebar main"
    "footer  footer";
  grid-template-columns: 240px 1fr;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }
3 Code Challenge
Challenge: Build a classic page layout (header, sidebar, main, footer) using grid-template-areas. Make the sidebar collapse to full-width on mobile using a media query.