Use Grid Shorthand to Visualize Explicit CSS Grid Tracks

Stephen Lindberg

Illustration of a CSS grid being drawn

If you’ve used CSS grid to set up an explicit grid, that is, with tracks that are named and sized explicitly, you may have written some rules like this:

.grid {
  display: grid;
    'head head'
    'menu main'
    'foot foot';

  grid-template-rows: 100px 1fr 200px;
  grid-template-columns: 200px 1fr;

I’ve used this pattern many times out of habit because it was the easiest way for me to remember and understand the grid setup. What I don’t like about this set of rules, though, is that the track sizes are separate from the grid area names. This adds a little friction when, say, I want to resize the height of the head section – which size declaration is that again? Oh, right, it’s 100px.

But what if we could combine all these rules into one shorthand rule which couples all the track sizes with their respective areas? That’s exactly what you can do with the grid shorthand rule.

Shorthand properties allow you to set several rules at once. border is one example of a shorthand property, which sets the rules border-width, border-style, and border-color in that order: border: 2px solid green. The grid shorthand allows you to define grid area names and track sizes together. An added bonus is that the CSS syntax allows formatting which can make vizualising your grid rules easier.

The syntax for the rule goes something like this:

grid: <row areas> <row size> / <column sizes>

with as many pairs of <row areas> <row size> as you need. With some clever wrapping and whitespace, we can align our areas and sizes to easily visualize the grid:

.grid {
  display: grid;
    'head  head' 100px
    'menu  main' 1fr
    'foot  foot' 200px
    /200px 1fr;

Take note that I’ve snuck the forward slash in right before the column sizes. Now go have fun with it!