2026-02-25|Formatting

CSS Grid Layout Guide: Master Two-Dimensional Layouts

What is CSS Grid?

CSS Grid Layout is a two-dimensional layout system that allows you to create complex page layouts with rows and columns. It is one of the most powerful layout tools in CSS.

Basic Grid Setup

.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: auto;
  gap: 20px;
}

The fr unit distributes available space proportionally.

Grid Template Areas

Define named areas for intuitive layout design:

.layout {
  display: grid;
  grid-template-areas:
    "header header header"
    "sidebar main aside"
    "footer footer footer";
  grid-template-columns: 200px 1fr 200px;
}

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

Placing Items

Spanning Multiple Columns

.wide-item {
  grid-column: span 2;
}

Spanning Multiple Rows

.tall-item {
  grid-row: span 3;
}

Responsive Grids with auto-fill

Create responsive layouts without media queries:

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

Alignment

Center Items in Grid Cells

.container {
  display: grid;
  place-items: center;
}

Distribute Space

.container {
  justify-content: space-between;
  align-content: center;
}

Grid vs Flexbox

  • Use Grid for 2D layouts (rows and columns)
  • Use Flexbox for 1D layouts (row or column)
  • They work great together — Grid for the overall layout, Flexbox for component internals

Common Patterns

Holy Grail Layout

.holy-grail {
  display: grid;
  grid-template: "header header" auto
                 "nav main aside" 1fr
                 "footer footer" auto
                / 200px 1fr 200px;
}

Card Grid

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