liveBook · Manning

Grid-template-columns

As explained in CSS in Depth, Second Edition

The CSS grid-template-columns property defines the sizes and optional names of a grid container's column tracks and grid lines.

Use `grid-template-columns` on a grid container to define its column tracks. `display: grid` establishes the container; the column template then determines how many columns it has and how their widths relate. A gap adds space between cells without becoming another column. section 5.1

Start with equal columns

For six items, `.grid { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 1fr 1fr; gap: 0.5em; }` produces three equal-width columns and two rows. Each `fr` represents a fraction of the available space. Change the template to `300px 1fr` when the first column should stay fixed and the second should fill the remaining space; `2fr 1fr` instead gives the first column twice the second column’s share. section 5.1

A three-column template also establishes four vertical grid lines: the outer edges and the two boundaries between columns. Items can use those lines for placement. For a page with a wide main area and a narrower sidebar, `grid-template-columns: 2fr 1fr` sets the proportions, while `grid-column` places the header, navigation, main area, and sidebar items. Those items must be children of the grid container. section 5.2

Name the boundaries you place against

When line numbers are hard to read, write `grid-template-columns: [left-start] 2fr [left-end right-start] 1fr [right-end];`. The middle boundary has two names, one for each side it separates. An item can then use `grid-column: left-start / right-end` to cross both columns. For repeated pairs of columns, `repeat(3, [col] 1fr 1fr)` lets placement refer to a particular occurrence with `grid-column: col 2 / span 2`. section 5.3.1

If an inner grid needs to follow its parent’s column lines, `grid-template-columns: subgrid` can use them, provided the parent defines those columns. This is a different choice from defining independent column widths on the inner grid. section 5.5

How CSS in Depth, Second Edition covers it

How deep it goes
Works through fraction-based sizing, mixed widths, named lines, repeated patterns, and parent-line inheritance with subgrid.
Examples
Uses a six-item grid, a main-content-and-sidebar page, and repeated named column lines.
What it assumes
Introduces grid containers, fraction units, tracks, and lines through basic layouts while using HTML and CSS examples.
What you can do after
Build it from scratch: size grid columns and name their boundaries for item placement.
How it connects
Connects grid tracks and lines to grid-column placement, repeat(), gap, and subgrid.

Also explained in

Compare how 4 books explain grid-template-columns →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of CSS in Depth, Second Edition. The section links point to the parts of the book it draws on.