Topic 48 of 62
Grid Placement
Overview
Once the Parent defines the Grid tracks, the Children normally auto-flow into the slots one by one. But the true power of Grid is that you can forcefully command any child to span across multiple rows/columns, or teleport to a completely different location on the board. You do this by targeting the invisible Grid Lines (the borders between the tracks).
Syntax
css
/*
If we have a 3x3 grid...
There are 4 vertical lines (1, 2, 3, 4) and 4 horizontal lines!
*/
.hero-image {
/* Span from vertical line 1, all the way to vertical line 4 (Full width) */
grid-column-start: 1;
grid-column-end: 4;
/* Shorthand: */
grid-column: 1 / 4;
}
.tall-banner {
/* Start at row line 1, span down 2 complete rows! */
grid-row: 1 / span 2;
}
.absolute-center {
/* Teleport this item to exactly Column 2, Row 2! */
grid-column: 2 / 3;
grid-row: 2 / 3;
}Common Pitfalls
- Confusing Grid Tracks (the actual columns) with Grid Lines. If you have 3 columns, you actually have 4 grid lines! (Line 1 is the far left edge, Line 4 is the far right edge). You place elements using the Lines.
- Forgetting the
-1trick. If you want an element to span the entire width of the grid, but you don't know how many columns there are, you don't have to guess.grid-column: 1 / -1;tells it to start at the first line and span all the way to the absolute last line, no matter what.
Interview Questions
Q:
What does the keyword
span do in CSS Grid placement?A:
Instead of declaring an explicit ending Grid Line number (which can be brittle if the grid changes), span 3 simply tells the browser 'start where you are, and stretch across 3 tracks'.
Real-World Example
Making a 'Featured Article' card span twice as wide and twice as tall as standard articles in a blog grid (Bento UI).
example
css
.featured-card {
/* Takes up a massive 2x2 block on the grid! */
grid-column: span 2;
grid-row: span 2;
}Check Your Knowledge
Test your understanding of Grid Placement with these quick questions.