Spanning Tracks with span Keyword
What you'll learn: How to make grid items span multiple tracks using the span keyword for cleaner, more readable code.
The Core Idea
Until now, you've been positioning grid items by specifying exact line numbers (like grid-column: 2 / 4). But what if you don't care where an item starts—you just want it to span a certain number of tracks? That's where the span keyword comes in.
Instead of counting line numbers, span lets you say "stretch across this many tracks" directly.
How span Works
The span keyword tells the browser how many tracks an item should occupy:
.item {
grid-column: span 2; /* spans 2 columns from wherever it's placed */
grid-row: span 3; /* spans 3 rows */
}
This is much clearer than calculating line numbers. The item will automatically start where the grid's auto-placement algorithm puts it, then stretch across the specified number of tracks.
Combining span with Line Numbers
You can also mix span with explicit positioning:
.item {
grid-column: 2 / span 3; /* starts at line 2, spans 3 columns */
grid-row: span 2 / 5; /* spans 2 rows, ends at line 5 */
}
Think of it like this: Imagine building a fence. Instead of saying "start at post 2 and end at post 5," you can say "start at post 2 and build 3 sections." That's what span does—it counts tracks, not lines.
When to Use span
Use span when:
- You care about size, not exact position
- You want flexible, maintainable layouts
- You're letting auto-placement handle positioning
Key Takeaway: The span keyword simplifies grid item sizing by letting you specify how many tracks to occupy, rather than calculating specific line numbers.