Topic 07 / 14

CSS Grid — Two-Dimensional Layout

~11 min read  //  CSS Series  //  Coding India

Rows AND Columns at Once

.layout {
  display: grid;
  grid-template-columns: 240px 1fr;     /* sidebar + flexible main */
  grid-template-rows: auto 1fr auto;    /* header, content, footer */
  gap: 1.5rem;
  min-height: 100vh;
}

The fr unit is a share of free space — 1fr 2fr splits leftover width 1:2.

repeat() & Sizing Functions

grid-template-columns: repeat(3, 1fr);          /* three equal columns */
grid-template-columns: repeat(4, minmax(0, 1fr)); /* equal even with long content */
grid-template-columns: 200px minmax(300px, 1fr); /* min/max constraints */

The One-Liner Responsive Gallery

The most valuable line of CSS in this series — cards that reflow to fit, no media queries:

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

Read it as: “as many columns as fit, each at least 280px, sharing leftover space equally.” Shrink the window and columns drop out automatically.

Placing Items

By default children fill cells in order. Override with line numbers:

.featured {
  grid-column: 1 / 3;      /* from line 1 to line 3 = span 2 columns */
  grid-row: 1 / 2;
}
.wide  { grid-column: span 2; }      /* simpler: just span */
.hero  { grid-column: 1 / -1; }      /* -1 = the last line → full width */

grid-template-areas — Layout You Can Read

.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  gap: 1rem;
}
.page header { grid-area: header; }
.page nav    { grid-area: sidebar; }
.page main   { grid-area: main; }
.page footer { grid-area: footer; }

The layout is literally drawn in the CSS — and rearranging for mobile is just redefining the map in a media query:

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

Alignment in Grid

.grid {
  place-items: center;        /* shorthand: align-items + justify-items */
}
.cell {
  place-self: end;            /* per-item override */
}

Centering anything: display: grid; place-items: center; — two lines.

Implicit Rows & Dense Packing

.gallery {
  grid-auto-rows: 200px;       /* rows created automatically get this height */
  grid-auto-flow: dense;       /* backfill holes left by spanning items */
}

Use DevTools’ grid inspector (the “grid” badge in the Elements panel) — it overlays line numbers and areas, and makes grid visually debuggable.