Place grid items on a grid using grid-column and grid-row

Rory Smith
InstructorRory Smith
Share this video with your friends

Social Share Links

Send Tweet

It’s possible to position a grid item anywhere on a grid track. To do this, let’s specify some grid-template-columns and grid-template-rows, and to the grid items, we’ll pass grid-column and grid-row some numeric values.

[00:00] In our markup, we have six grid items inside a container. In our CSS, our container is display-grid with a 20-pixel gutter, and it's taking up the available viewport height.

[00:11] On every grid-item is a blue background color just for visibility. Let's give our grid some grid-template-columns. Let's say, we want four columns. In this case, the first column is 100 pixels, the second is 200, and the third and fourth are set to auto, so they're going to take up the available space evenly.

[00:38] This looks fine, but we've got this gap down here that isn't being filled by any grid items because they're being evenly spread. We can change where grid items appear on our grid, so we can position them in different places. Let's say, we wanted to fill this space with our sixth grid item, and then with the space that remains here, we can fill with the second grid item.

[01:05] To do that, let's start by targeting our sixth grid item. In each of our grid items, we can specify where on the grid they're placed, and we can do that with grid-row-start and grid-row-end, and grid-column-start and grid-column-end.

[01:23] For our sixth grid item, we want it to start on the third column, so we're going to say grid-column-start:3, and it's moved over to the third column. We want it to fill this space, so we're going to say grid-column-end:5.

[01:46] The reason it's 5 and not 4, is because these numbers we're using are referring to our grid lines, and this last column line is the fifth column line. We've got one, two, three, four, and five.

[02:03] We could also achieve this using the span keyword. Instead of specifying the grid line, we could just say that we want it to span across two columns, and we get the same result. Now, we need to fill this available space with our second grid item, so we can apply the same logic.

[02:23] Let's target the second one and we're going to say grid-row-start this time instead of column, because we're targeting this row down here, and we can say grid-row-start:span 2, and now our second grid item is spanning across two rows.

[02:41] Finally, there's a shorthand property that we can use to define both of these at once. To do that, we just omit the start or end suffixes.

[02:52] For our sixth grid item, we could say grid-column:3/span 2, and we get the same results. To verify that's what's happening, let's look under the hood and we can see the rules being applied here with the shorthand rule.