šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Defining names for lines in CSS grid

The CSS Grid uses lines to position the elements. By default, we can use line numbers to place the elements.

But if you find notations like .header { grid-column: 1 / 3; } confusing then we can define name for these lines.

The name defining is done in the grid-template-columns (and, if needed, in the grid-template-rows):

.container {
    display: grid;
    grid-template-columns: [article-start] 2fr [picture-start] 1fr [nav-start] 80px [nav-end];
}

So now we can say:

.header {
    grid-column: article-start / nav-start;
}
.article {
    grid-column: article-start/picture-start;
}
.picture {
    grid-column: picture-start / nav-start;
}
.navigation {
    grid-column: nav-start / nav-end;
}

Check out below the full working example.

See the Pen
Using names for CSS grid lines
by JS Craft (@js-craft)
on CodePen.

Defining multiple names for the same lines

But wait, there is more! We can define more that one name for a line.

It would be cool to define our article with something like article-start to article-end.

However, the article-end will be the starting point for the picture section. This means that we will then have to write for the picture: grid-row: article-end / nav-start; instead of an ideal grid-row: picture-start / picture-end;

In most cases, the ending point for something is the starting point for something else. So, therefore, the need to have multiple names for the same line.

We can implement this by just adding an extra name in the square brackets.

.container {
  grid-template-columns: 
      [article-start] 
      2fr 
      [article-end picture-start] 
      1fr 
      [picture-end nav-start] 
      80px 
      [nav-end];
}

So that we can now say:

.picture {
    grid-row: picture-start / picture-end;
}

Check out here the codepen with multiple names for the same lines. Cheers!

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *