CSS Grid
CSS Grid is a layout system for rows and columns together. Make a container with display: grid, and describe the columns, and the items fall into the cells.
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 10px;
}
Three equal columns
1
2
3
4
5
6
The fr unit
fr means “fraction of the free space”. 1fr 2fr makes two columns, the second twice as wide as the first. You can mix units.
grid-template-columns: 200px 1fr; /* fixed sidebar and flexible content */
grid-template-columns: repeat(4, 1fr); /* four equal columns */
Container properties
| Property | Use |
|---|---|
grid-template-columns | Sizes of the columns |
grid-template-rows | Sizes of the rows |
gap | Space between cells |
justify-items, align-items | Alignment of items inside their cells |
Span cells
.wide { grid-column: span 2; }
.tall { grid-row: span 2; }
.header { grid-column: 1 / -1; } /* from first to last line */
Output in the browser
Header: spans all columns
Menu
Content: spans 2 columns
Responsive grid without media queries
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}
This makes as many columns as fit, each at least 200px wide. On a phone the cards stack by themselves.
Note:
Flexbox is best for one direction (a menu, a row of buttons). Grid is best for page layouts and card galleries. They work well together.
Summary
display: gridwithgrid-template-columnsmakes a grid.- Use
fr,repeat()andgap. - Use
auto-fitwithminmax()for responsive cards. - Next: Pseudo-classes and pseudo-elements.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |