HTML/CSS Mastery

CSS Grid Layouts

35 min

Grid controls rows and columns at once. Use it for page layouts and card grids; use flexbox inside the cells.

A basic grid

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
}

fr is a fraction of the free space: 1fr 2fr makes the second column twice as wide.

Responsive cards without media queries

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 20px;
}

The browser fits as many 260px+ columns as it can and stretches them to fill the row. One line handles phones to wide screens.

Note: auto-fit/auto-fill can leave a lonely card on the last row at some widths. For a fixed design, use explicit breakpoints: 1 column on phones, 2 on tablets, 3 on desktop.

Page layout with named areas

.page {
  display: grid;
  grid-template-columns: 260px minmax(0, 1fr);
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  min-height: 100vh;
}
header { grid-area: header; }
aside  { grid-area: sidebar; }
main   { grid-area: main; }
footer { grid-area: footer; }

@media (max-width: 800px) {
  .page {
    grid-template-columns: minmax(0, 1fr);
    grid-template-areas: "header" "main" "sidebar" "footer";
  }
}

Use minmax(0, 1fr) rather than 1fr for content columns: a plain 1fr cannot shrink below its content, so long code lines or URLs can widen the page on phones.

Placing items

.feature { grid-column: span 2; }        /* take two columns */
.hero { grid-column: 1 / -1; }           /* full width */
.photo { grid-row: span 2; }

Aligning

.grid { align-items: start; justify-items: center; }
.cell { align-self: end; }
place-items: center;      /* both at once */

Grid or flexbox?

Situation Choose
Items in one line that should wrap naturally flexbox
Rows and columns must align grid
Whole page structure grid
Inside a card or button flexbox

Exercise

Build a dashboard: header across the top, sidebar on the left, a main area with a 4-column stats row (2 columns on tablets, 1 on phones) and a card grid using auto-fill. Collapse the sidebar under the main content below 800px.

Check yourself

  • What does 1fr mean?
  • How does repeat(auto-fill, minmax(260px, 1fr)) create a responsive grid?
  • Why use minmax(0, 1fr) for content columns?

Your progress is saved in this browser only.

Submit for review (10 points)