Get Started with CSS Grid - Examples Included
CSS Grid is a layout system that allows you to create complex layouts with ease. It is based on the idea of a grid, and you can use it to arrange your content in rows and columns.
To use CSS Grid, you first need to set the display
property of the container element to grid
. You can then use the grid-template-columns
and grid-template-rows
properties to define the number and size of the rows and columns in the grid.
For example, the following code would create a grid with two columns and three rows:
.container {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(3, 1fr);
}
You can then use the grid-area
property to place your content in the grid. For example, the following code would place an image in the first column and first row of the grid:
.image {
grid-area: 1 / 1;
}
You can also use the grid-template-areas
property to define the layout of the grid. For example, the following code would create a grid with four areas:
.container {
display: grid;
grid-template-areas:
"header header"
"content content"
"footer footer";
}
You can then use the grid-area
property to place your content in the grid areas. For example, the following code would place an image in the header area:
.image {
grid-area: header;
}
CSS Grid is a powerful layout system that can be used to create complex layouts with ease. It is a great choice for websites that need to be responsive and adaptable to different screen sizes.
Here are some examples of CSS Grid layouts:
- A two-column layout: This is a simple layout that can be used to divide the content of a page into two columns. The following code would create a two-column layout:
.container {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
- A three-column layout: This is a more complex layout that can be used to divide the content of a page into three columns. The following code would create a three-column layout:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
- A four-column layout: This is a even more complex layout that can be used to divide the content of a page into four columns. The following code would create a four-column layout:
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
- A fluid layout: This is a layout that can adapt to different screen sizes. The following code would create a fluid layout:
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
- A responsive layout: This is a layout that can adapt to different screen sizes and orientations. The following code would create a responsive layout:
@media (max-width: 768px) {
.container {
display: grid;
grid-template-columns: repeat(1, 1fr);
}
}
@media (max-width: 480px) {
.container {
display: grid;
grid-template-columns: repeat(1, 100%);
}
}
These are just a few examples of CSS Grid layouts. There are many other possibilities, and you can use CSS Grid to create any layout you can imagine.