CSS Grid Summary
Grid is a CSS layout tool for making rows and columns. It is useful when you want boxes to line up in a clear page structure.
.cards {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
Grid Containers And Grid Items
Grid starts by adding display: grid; to a parent element. The direct children inside that parent become grid items.
.cards {
display: grid;
}
Grid is commonly used for card layouts, image galleries, product lists, and larger page layouts.
Columns
grid-template-columns controls the number and size of columns.
.cards {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
This creates three equal columns. The unit fr means a share of the available space.
Gap
Gap adds space between grid items. It creates space between the rows and columns.
.cards {
display: grid;
gap: 20px;
}
Responsive Grid
A grid can change for different screen sizes. On a phone, cards may stack in one column. On a wider screen, they can move into multiple columns.
.cards {
display: grid;
gap: 20px;
grid-template-columns: 1fr;
}
@media (min-width: 700px) {
.cards {
grid-template-columns: 1fr 1fr 1fr;
}
}
This is a common mobile-first pattern. The one-column layout comes first. The larger layout is added later.
Grid Versus Flex
Flex is often good for one row or one line of items. Grid is often good when you want both rows and columns.
For many beginner layouts, either one can work. The main point is to use the tool that makes the layout easiest to understand.
Common Grid Uses
Grid is used often for three-card sections, blog post lists, service boxes, image galleries, pricing tables, and dashboard-style layouts.