Skip to main content

Grid Lines

In CSS Grid Layout, grid lines are the dividing lines that separate the grid into rows and columns. They are the foundational elements that define the structure of the grid, helping you place and align grid items.

Basic Concepts

  1. Line Numbering: Grid lines are numbered starting from 1. The numbering starts from the top-left corner for both rows and columns. Negative numbering starts from the bottom-right corner.

  2. Line Names: You can also name grid lines for easier reference.

  3. Gaps: Grid lines also help in defining gaps (or "gutters") between grid items.

Sample of gridlines

grids The image shows how grid lines are created and numbered.

  1. grid-template-rows and grid-template-columns: Define the size of the tracks between grid lines.

    .grid-container {
    grid-template-rows: 100px 200px;
    grid-template-columns: 1fr 2fr;
    }
  2. grid-row-start, grid-row-end, grid-column-start, grid-column-end: Place grid items between specific grid lines.

    .grid-item {
    grid-row-start: 1;
    grid-row-end: 3;
    }
  3. grid-gap: Defines the size of the gap between grid lines.

    .grid-container {
    grid-gap: 10px;
    }

Practical Examples

  1. Using Line Numbers

    .grid-item {
    grid-column: 1 / 3; /* From line 1 to line 3 */
    }
  2. Using Named Lines

    .grid-container {
    grid-template-columns: [start] 1fr [middle] 1fr [end];
    }
    .grid-item {
    grid-column: start / end;
    }
  3. Using Negative Line Numbers

    .grid-item {
    grid-column: 1 / -1; /* Spans the entire width of the grid */
    }

Best Practices

  1. Semantic Naming: Use meaningful names for grid lines, especially when the layout is complex.

  2. Responsive Design: Adjust grid lines using media queries to adapt to different screen sizes.

  3. Accessibility: Ensure that the layout remains accessible and logical when grid items are rearranged.

Limitations and Considerations

  • Grid lines exist on the periphery of the grid container as well, not just between grid items.
  • Named lines are helpful but can become cumbersome in very complex layouts.