AskDB
·7 min read

CSS Grid Guide

CSS Grid is the most powerful layout system in CSS. It handles two-dimensional layouts (rows and columns) with precision.

Grid Container

.grid {
  display: grid;

  /* Define columns */
  grid-template-columns: 200px 1fr 200px;
  grid-template-columns: repeat(3, 1fr);
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

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

  /* Gap */
  gap: 16px;
  row-gap: 16px;
  column-gap: 16px;

  /* Named areas */
  grid-template-areas:
    "header header header"
    "sidebar main aside"
    "footer footer footer";
}

Grid Item Placement

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

  /* By span */
  grid-column: span 2;     /* span 2 columns */

  /* By area name */
  grid-area: header;

  /* Alignment */
  justify-self: center;    /* horizontal within cell */
  align-self: center;      /* vertical within cell */
}

fr Unit

/* fr = fraction of available space */
grid-template-columns: 1fr 2fr 1fr;
/* 25% | 50% | 25% of available space */

grid-template-columns: 1fr 1fr;
/* Two equal columns */

auto-fit and minmax

/* Responsive grid without media queries */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
/* Items are min 250px, grow to fill, auto-wrap */

Common Patterns

Holy Grail Layout

.layout {
  display: grid;
  grid-template-areas:
    "header header header"
    "sidebar main aside"
    "footer footer footer";
  grid-template-columns: 200px 1fr 200px;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}
.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.aside   { grid-area: aside; }
.footer  { grid-area: footer; }

Responsive Card Grid

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
}

Dashboard Layout

.dashboard {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: minmax(200px, auto);
  gap: 16px;
}
.widget-wide { grid-column: span 2; }
.widget-tall { grid-row: span 2; }

Grid vs Flexbox

  • Grid — 2D layout (rows + columns together)
  • Flexbox — 1D layout (row OR column)
  • Grid is better for page layouts, dashboards, galleries
  • Flexbox is better for navbars, card content, inline layouts
  • They work great together — Grid for page structure, Flex for components