CSS Grid

Positioning items

We can position a grid item exactly where we want it using the grid-row-start, grid-row-end, grid-column-start and grid-column-end properties.

Syntax

.item1 {
grid-row-start: 1;
grid-row-end: 2;
}

The above code positions .item1 at row 1 and spans to the next row (row 2). The syntax and meaning for columns is identical.

Shorthand syntax

grid-row is a shorthand for the combination of grid-row-start and grid-row-end, and can be used to specify just the first property if only one value is given.

grid-column is a shorthand for the combination of grid-column-start and grid-column-end, and can be used to specify just the first property if only one value is given.

grid-area is a shorthand for the combination of grid-row-start, grid-column-start, grid-row-end and grid-column-end in that exact order, and can be used to specify any one, two, three or all four values depending on the number of values given.

.item1 {
grid-area: 1 / 2 / 3 / 4;
}

is equivalent to

.item1 {
grid-row: 1 / 3;
grid-column: 2 / 4;
}

and equivalent to the even longer version

.item1 {
grid-row-start: 1;
grid-row-end: 3;
grid-column-start: 2;
grid-column-end: 4;
}

Span keyword

Keeping track of absolute row and column grid line numbers is an error-prone process. The span keyword makes it possible to span a row or column the given amount.

.item1 {
grid-row: 1 / span 2;
}

is equivalent to

.item1 {
grid-row: 1 / 3;
}

Code example: spanning item across columns

In the below example, we have created a 2x3 layout and chosen to span .item3 across two columns using grid-column-start and grid-column-end. Notice how this pushes .item4 to the next row.

<div class="wrapper">
<div class="item" id="item1">1</div>
<div class="item" id="item2">2</div>
<div class="item" id="item3">3</div>
<div class="item" id="item4">4</div>
<div class="item" id="item5">5</div>
</div>
.wrapper {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(3, 1fr);
}
.item3 {
background: green;
grid-column-start: 1;
grid-column-end: 2;
}
1
2
3
4
5