robohash image acting as kam's profile photo

Tip 027 - Named Grid Lines


So hey, have you tried CSS Grid yet? Pretty neat, amirite? Well it gets neater.

When you say grid-template-columns you start listing out all the tracks (columns) that are in your grid and what their sizes are. Same with rows, but with grid-template-rows. Example:

.grid {
  display: grid;
  grid-template-columns: 3fr 1fr;

Hooray, now you have a grid with two columns, sized at 75% and 25%, respectively.

Consider two potential problems here. First, with complicated layouts, you may well have a ton of columns in your grid, and that CSS rule can get real hefty. How do you say which line a div starts on, when you can't remember offhand how many lines there even are? Second, how do you maintain the declarations on the grid items? If you add lines or items to the grid it suddenly becomes a mess of remembering which line numbers go where. Custom Properties can only take us so far, after all.

Turns out you can name all the grid lines! It's as simple as picking a name, wrapping it in square brackets, and sticking it in the template declaration where it belongs: (bonus: you can give a line multiple names by separating them with a space and use any of them)

.grid {
  display: grid;
  grid-template-columns: [beginning] 3fr [middle another-name] 1fr [end];

This may be really funky to think about. In one declaration, we are saying how many tracks there are, what the sizes of those tracks are, and what all the lines surrounding them are named. It almost seems like it's too much for one line to do. Geddski explained it very well with an illustration of alternating lines and tracks. In the CSS, you declare everything from left to right (or top to bottom) naming lines and declaring sizes along the way.

Once your lines are named, your grid items can be placed based on the name of the line instead of the line number:

.grid .item {
  grid-column: middle / end;
    /* OR */
  grid-column-start: another-name;
  grid-column-end: end;

Now you can move the names around your template and watch your grid items move. More points for CSS! Enjoy the easy maintenance!


Have you written a reply on another site? Put the URL here: