CSS Grid Layout is a two-dimensional system for creating complex web layouts using both rows and columns.
display: grid
The display: grid
property defines the element as a grid container. Once set, its direct children become grid items.
.container { display: grid; }
grid-template-columns
This property defines the number of columns and their sizes in the grid container.
.container { grid-template-columns: 200px 1fr 2fr; }
grid-template-rows
This property defines the number of rows and their sizes in the grid container.
.container { grid-template-rows: 100px 200px; }
grid-gap
The grid-gap
property defines the space between rows and columns.
.container { grid-gap: 20px; }
grid-template-areas
The grid-template-areas
property allows you to define named grid areas for the layout.
.container { grid-template-areas: "header header header" "sidebar content content" "footer footer footer"; }
grid-column
This property specifies the horizontal placement of a grid item.
.item { grid-column: 1 / 3; }
grid-row
This property specifies the vertical placement of a grid item.
.item { grid-row: 2 / 4; }
grid-area
This property allows you to place grid items into specific named grid areas.
.item { grid-area: header; }
With media queries, you can make your grid layouts responsive to different screen sizes.
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr 1fr;
}
}
@media (max-width: 480px) {
.container {
grid-template-columns: 1fr;
}
}
CSS Grid and Flexbox can be combined to create more complex layouts. In this example, Flexbox is used within a grid item.
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
.item {
display: flex;
justify-content: center;
align-items: center;
background-color: lightblue;
height: 150px;
}