Span rows and columns in CSS grid
25 Spanning rows and columns
fairMake one tile twice as wide and another twice as tall inside a four-column grid, using line numbers and the span keyword.
Stuck? Three hints, smallest first
- 1.
grid-column: span 2is shorthand for “take two tracks from wherever you land”. - 2.
grid-row: 1 / 3names the start and end lines, and lines are counted from 1, not 0. - 3. A grid with four columns has five column lines. Off-by-one here is the usual bug.
<ul class="mosaic">
<li class="wide">wide, span 2</li>
<li class="tall">tall, rows 1 to 3</li>
<li>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>
.mosaic {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 48px;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
}
/* Two tracks wide, starting wherever the auto-placer puts it. */
.wide { grid-column: span 2; }
/* Explicit lines. Four columns means five lines, so 1 / 3 covers two rows. */
.tall { grid-row: 1 / 3; }
.mosaic li {
display: grid;
place-items: center;
background: #eef1fd;
border: 1px solid #3055d8;
border-radius: 6px;
font-size: 0.78rem;
text-align: center;
}
.wide { background: #d9dcea; }
.tall { background: #cfd6f3; }
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// A grid of N columns has N + 1 lines. Getting that wrong is the classic bug.
const columns = Number(/repeat\((\d+), 1fr\)/.exec(css)[1]);
const lines = columns + 1;
const rowSpan = (/grid-row:\s*(\d+) \/ (\d+)/.exec(css) || []).slice(1).map(Number);
test('four columns', columns, 4);
test('which means five column lines', lines, 5);
test('the tall tile runs from line 1 to line 3', rowSpan, [1, 3]);
test('so it covers two rows', rowSpan[1] - rowSpan[0], 2);
test('the wide tile uses the span keyword instead', /grid-column:\s*span 2/.test(css), true);
test('rows created on the fly have a set height', /grid-auto-rows:\s*48px/.test(css), true);
test('six tiles', countTag(html, 'li'), 6);
test('no absolute positioning was used to overlap them', /position:\s*absolute/.test(css), false);
Output
Line numbers and span answer different questions. span 2 says “two tracks from wherever I land”, so it survives reordering; 1 / 3 says “these exact lines”, which is what you want when the position is the point. The arithmetic in the second check is the thing to internalise: four columns have five lines, so 1 / 3 spans two tracks and not three. grid-auto-rows is the companion detail — rows the auto-placer creates have no height rule of their own otherwise, so they collapse to their content.