Use Display Grid To Lay Out Elements

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

Use display with the value grid to lay out items in a grid. You can specify the number of columns and rows using grid-template-columns and grid-template-rows.

Instructor: [0:00] We want to lay out the board for our tic tac toe game in a 3x3 grid. We're going to start by defining a CSS variable for the size of our grid, and we're going to go with 50vmin. We're going to apply that size to our board with height: var(--size) and width: var(--size).

[0:19] We're going to lay this out in a grid using display: grid. For our grid, we want three columns. We can use grid-template-columns: 1fr 1fr 1fr. That gives us three equal-width columns, because we're using three fractions. Alternatively, we could write this as repeat(3, 1fr).

[0:38] If we look in DevTools, we can now see that our board has a 3x3 grid. That's because we defined three columns, and we have a height and width. Because we have nine elements implicitly, we get three rows, but we could also explicitly set the rows with grid-template-rows: repeat(3, 1fr).

[0:57] Lastly, to align things, let's use place-items: center. Now, we can see the cells in our grid have all been centered within their grid position.

[1:06] In review, we can use display: grid to lay out items where we use grid-template-columns and grid-template-rows to set the number of columns and rows for our grid. We can then use place-items to align the content within each grid position.