CSSCSS · Lesson 5 of 9

CSS Grid

CSS Grid is the layout system we've wanted since 1996. It arrived in 2017. Better late than never, we suppose.

CSS
/* CSS Grid basics */
.grid-container {
  display: grid;

  /* Define columns */
  grid-template-columns: 200px 1fr 2fr;          /* 3 cols: fixed, flexible */
  grid-template-columns: repeat(3, 1fr);           /* 3 equal columns */
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));  /* responsive */

  /* Define rows */
  grid-template-rows: 60px 1fr auto;

  /* Template areas — visual layout map */
  grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";

  gap: 20px;           /* gap between rows and columns */
  row-gap: 10px;
  column-gap: 20px;
}

/* Place items in areas */
.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

/* Or use line numbers */
.item {
  grid-column: 1 / 3;   /* from line 1 to line 3 (spans 2 columns) */
  grid-row: 2 / 4;      /* from line 2 to line 4 */
}

/* span keyword */
.wide-item {
  grid-column: span 2;   /* span 2 columns from wherever it is */
}
CSS
/* Real-world grid examples */

/* Classic page layout */
.page {
  display: grid;
  grid-template-areas:
    "nav"
    "hero"
    "content"
    "footer";
  grid-template-rows: 60px 400px 1fr auto;
  min-height: 100vh;
}

@media (min-width: 768px) {
  .page {
    grid-template-areas:
      "nav     nav"
      "hero    hero"
      "sidebar content"
      "footer  footer";
    grid-template-columns: 250px 1fr;
  }
}

/* Auto-responsive card grid (no media queries needed) */
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
}

/* Image gallery */
.gallery {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: 200px;
  gap: 8px;
}

.gallery .featured {
  grid-column: span 2;
  grid-row: span 2;
}