Course contentsShow
← Web Development
Lesson 348 of 2,9826. CSS GridFree lesson

Negative Line Numbers

Counting grid lines from the end using negative numbers for flexible placement.

Negative Line Numbers

You'll learn: How to count grid lines backwards from the end to position items flexibly, without needing to know the total number of tracks.

What Are Negative Line Numbers?

In CSS Grid, you can count grid lines from the end using negative numbers instead of from the beginning with positive ones. -1 refers to the last line, -2 to the second-to-last, and so on. This is incredibly useful when you want to position items relative to the grid's end without knowing exactly how many columns or rows exist.

Why Use Negative Numbers?

Imagine you want a footer to always span from the left edge to the right edge of your grid. If your grid has 3 columns, you'd use lines 1 to 4. But what if the grid is responsive and sometimes has 4, 6, or 12 columns? You'd need to constantly update your code.

With negative line numbers, you can say: "Start at line 1 and end at line -1" — meaning "stretch from the beginning to the very end," regardless of how many tracks exist.

How It Works

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
}

.full-width-item {
  grid-column: 1 / -1;  /* First line to last line */
}

.right-aligned {
  grid-column: -3 / -1;  /* Third-to-last to last */
}

Think of it like counting floors in a building: you can say "5th floor from the ground" or "2nd floor from the roof" — both tell you exactly where to go.

Key Takeaway: Negative line numbers count backwards from the end of your grid (-1 = last line), making it easy to position items relative to the grid's end without hardcoding total track counts.