Grid: laying out a page
Columns and rows at the same time: the fr unit, grids that fit themselves to the screen with no media query, placing items across several columns, and naming the areas of a page.
By the end you can
- Build a grid with columns that share the space fairly
- Make a gallery that rearranges itself with no media query
- Make one item span several columns or rows
- Lay out a whole page by naming its areas
Easier if you did first
step 1 of 4
Columns, and the fr unit
Flexbox arranges things along one line. Grid works in two directions at once: columns and rows together.
The rule of thumb: flexbox for a row of things, grid for the shape of a page or a gallery.
display: grid turns a box into a grid. Then grid-template-columns says how many columns there are and how wide each one is.
You could write it in pixels, but then the layout only fits one screen size. Grid has its own unit for sharing space: fr, short for fraction.
grid-template-columns: 1fr 1fr 1fr means three columns that split the available space equally. 2fr 1fr means the first column gets twice as much as the second. The browser does the arithmetic, including the gaps, which is the part that makes percentages so painful.
repeat(3, 1fr) is the shorthand for three equal columns, and it is what you will usually write.
gap works exactly as it does in flexbox, and here it can take two values: rows then columns.
Make the gallery on the right a three-column grid.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
}
1fr 1fr 1fr three equal columns
2fr 1fr the first is twice the second
200px 1fr a fixed sidebar, then the rest
gap: 24px 12px 24 between rows, 12 between columnsWhat these words mean
- display: grid
- Arrange this element's children in columns and rows.
- grid-template-columns
- How many columns, and how wide each is.
- fr
- A fraction of the space left over. The grid unit for sharing.
- repeat()
- Shorthand: repeat(3, 1fr) is 1fr 1fr 1fr.
- gap
- Space between the cells. One value for both, or rows then columns.
Easy to get wrong
grid-template-columns: 33% 33% 33% with a gap
repeat(3, 1fr)
The percentages do not know about the gaps, so three 33% columns plus two gaps is wider than the container and the last column drops to the next line. fr accounts for the gaps automatically.
Using grid for a single row of buttons
flexbox
Grid asks you to describe the columns up front. For one line of items that just need to sit together, flex is less to write and less to maintain.
What we check
- .gallery is a grid
- The columns are described
- The columns share the space with fr
- Six tiles have landed on two rows of three
- The columns are equal in width