NelsonLabs
CSS Styling/CSS Grid

CSS Grid

CSS Grid is the first real two-dimensional layout system on the web. While Flexbox handles one axis (row or column), Grid controls both simultaneously. It's what makes complex page layouts simple.

ANALOGY

A spreadsheet for layout. CSS Grid turns the page into a spreadsheet โ€” defined rows and columns โ€” where you can place any element in any cell, span across multiple cells, or let items flow automatically. Flexbox is one shelf; Grid is the entire shelving unit.

Grid fundamentals
css
/* Define a grid container */
.container {
  display: grid;

  /* Define columns */
  grid-template-columns: 200px 1fr 200px; /* sidebar | content | sidebar */
  grid-template-columns: repeat(3, 1fr);  /* 3 equal columns */
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* responsive! */

  /* Define rows */
  grid-template-rows: auto 1fr auto; /* header | main | footer */

  /* Gaps between cells */
  gap: 1.5rem;             /* same gap for rows and columns */
  gap: 1rem 2rem;          /* row-gap  column-gap */
}
Placing items on the grid
css
/* Items go into the next available cell by default */
/* You can also explicitly place them */

.header {
  grid-column: 1 / -1;    /* span from first to last column */
}

.sidebar {
  grid-column: 1 / 2;     /* columns 1 to 2 */
  grid-row: 2 / 4;        /* rows 2 to 4 */
}

.main {
  grid-column: 2 / 3;
  grid-row: 2 / 3;
}
Grid template areas โ€” most readable approach
css
.page {
  display: grid;
  grid-template-areas:
    "header  header  header"
    "sidebar content aside"
    "footer  footer  footer";
  grid-template-columns: 200px 1fr 160px;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}

.page-header  { grid-area: header; }
.page-sidebar { grid-area: sidebar; }
.page-content { grid-area: content; }
.page-aside   { grid-area: aside; }
.page-footer  { grid-area: footer; }

TIP

Responsive grid in one line. grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)) creates a grid where columns are at least 250px wide. If there's room for more, it adds them. On a narrow screen, items stack into one column. No media queries needed. This is one of the most powerful one-liners in CSS.