Abdellah El Mennani
Abdellah El Mennani

Reputation: 268

What is the benefit of naming grid lines?

What are the benefit of naming grid lines in CSS Grid Layout? I have seen many examples doing so, I wondered what is the benefit? Why not just rely on the line numbers, instead of, for example, first-column-start?

Upvotes: 2

Views: 713

Answers (2)

Fatih Hayrioğlu
Fatih Hayrioğlu

Reputation: 3506

Good define

Naming grid lines gives you hooks into your grid where you can attach your content.

https://gedd.ski/post/naming-css-grid-lines/

Upvotes: 0

Michael Benjamin
Michael Benjamin

Reputation: 371929

Short Answer

Named grid lines make the code easier to understand and maintain.


Explanation

Grid lines are the horizontal and vertical dividing lines of the grid.

A column or row is formed in between two parallel grid lines.

A grid cell is formed by intersecting grid lines.

enter image description here

source: W3C CSS Grid Specification

(block axis / inline axis definitions)

A grid line can be referenced numerically or by a defined name. Both rules below are the same.

#grid-container {
    grid-template-rows: 2em 1fr 3em;
}

#grid-container {
    grid-template-rows: [header-start] 2em [header-end body-start] 1fr [body-end footer-start] 3em [footer-end];
}

Note that lines can have multiple names.

In laying out the grid, we could just use numerical values, like this:

#grid-item-1 { grid-row: 1 / 2; } /* the header */

#grid-item-2 { grid-row: 2 / 3; } /* the content */

#grid-item-3 { grid-row: 3 / 4; } /* the footer */

Or, to make things easier to understand and maintain (think of coming back to this code a year later, or passing this code on to other developers), use meaningful names instead:

#grid-item-1 { grid-row: header-start / header-end; }

#grid-item-2 { grid-row: body-start / body-end; }

#grid-item-3 { grid-row: footer-start / footer-end; }

Code sample:

article {
  display: grid;
  grid-template-rows: [header-start] 2em [header-end body-start] 1fr [body-end footer-start] 3em [footer-end]; }

}
section:nth-child(1) { grid-row: header-start / header-end; }

section:nth-child(2) { grid-row: body-start / body-end; }

section:nth-child(3) { grid-row: footer-start / footer-end;}

/* non-essential demo styles */
article {
  grid-gap: 1px;
  background-color: gray;
  height: 100vh;
  border: 1px solid gray;
}
section {
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}
section:nth-child(1) { background-color: aqua; }
section:nth-child(2) { background-color: orange; }
section:nth-child(3) { background-color: lightgreen; }
body                 { margin: 0;}
*                    { box-sizing: border-box; }
<article>
  <section>header</section>
  <section>body</section>
  <section>footer</section>
</article>

More information: https://www.w3.org/TR/css3-grid-layout/#named-lines

Upvotes: 1

Related Questions