HTML CSS - Grid
Creating complex layouts with CSS Grid
CSS Grid Layout is a powerful layout system in CSS. It allows for the creation of complex layouts using rows and columns. This tutorial covers the basics of creating complex layouts with CSS Grid.
Key Points:
- The
display: grid
property enables the Grid layout on a container. - Grid layout uses rows and columns to create complex layouts.
- Grid properties include
grid-template-rows
,grid-template-columns
,grid-gap
, and more.
Basic Grid Container
To create a Grid layout, you need to apply display: grid
to a container element. Here is an example:
.grid-container {
display: grid;
gap: 10px;
background-color: lightgray;
padding: 10px;
}
.grid-item {
background-color: #4CAF50;
padding: 20px;
text-align: center;
color: white;
}
Defining Rows and Columns
The grid-template-rows
and grid-template-columns
properties define the number and size of rows and columns. Here is an example:
.grid-container {
display: grid;
grid-template-rows: 100px 200px;
grid-template-columns: 1fr 2fr;
gap: 10px;
}
Grid Gap
The gap
property (also known as grid-gap
) sets the space between grid items. Here is an example:
.grid-container {
display: grid;
gap: 20px;
}
Grid Item Placement
You can place grid items in specific rows and columns using the grid-row
and grid-column
properties. Here is an example:
.grid-container {
display: grid;
grid-template-rows: repeat(3, 100px);
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.grid-item:nth-child(1) {
grid-column: 1 / 3;
}
.grid-item:nth-child(2) {
grid-row: 2 / 4;
}
Grid Template Areas
The grid-template-areas
property allows you to define grid areas and place grid items into these areas. Here is an example:
.grid-container {
display: grid;
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
gap: 10px;
}
.grid-item-header {
grid-area: header;
}
.grid-item-sidebar {
grid-area: sidebar;
}
.grid-item-content {
grid-area: content;
}
.grid-item-footer {
grid-area: footer;
}
Summary
In this tutorial, you learned about creating complex layouts with CSS Grid. You explored the basic Grid container, defining rows and columns, using grid gap, placing grid items, and defining grid template areas. CSS Grid provides a powerful and flexible way to create responsive and complex layouts, making it an essential tool for modern web design.