In this lesson, we will explore the CSS Grid Layout, a powerful tool for creating complex and responsive layouts with ease. We will learn how to create a grid container, define rows and columns, and position items within the grid.
- Introduction to CSS Grid Layout
- Creating a Grid Container
- Defining Rows and Columns
- Placing Items in the Grid
- Grid Template Areas
- Responsive Design with CSS Grid
Table of Contents
Introduction to CSS Grid Layout
CSS Grid Layout is a two-dimensional layout system that allows you to create intricate designs with ease. With the grid layout, you can control both rows and columns, making it suitable for a wide range of applications.
Creating a Grid Container
To create a grid container, apply the display: grid;
property to an HTML element:
<div class="grid-container">
<!-- Grid items go here -->
</div>
.grid-container {
display: grid;
}
Defining Rows and Columns
Use the grid-template-rows
and grid-template-columns
properties to define the size of rows and columns in the grid:
.grid-container {
display: grid;
grid-template-rows: 100px 200px;
grid-template-columns: 1fr 2fr;
}
Placing Items in the Grid
Grid items are automatically placed in the grid according to the row and column definitions. To manually position items, use the grid-row
and grid-column
properties:
<div class="grid-container">
<div class="grid-item item1">1</div>
<div class="grid-item item2">2</div>
</div>
.item1 {
grid-row: 1;
grid-column: 1;
}
.item2 {
grid-row: 2;
grid-column: 2;
}
Grid Template Areas
Grid template areas allow you to create a layout using named areas, making it easier to understand and maintain. Use the grid-template-areas
property in the container and the grid-area
property in the items:
.grid-container {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.main {
grid-area: main;
}
.footer {
grid-area: footer;
}
Responsive Design with CSS Grid
CSS Grid makes it easy to create responsive designs using media queries:
@media screen and (max-width: 768px) {
.grid-container {
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
}
}
Actionable Work
- Create an HTML file with several elements to be used as grid items.
- In a separate CSS file, create a grid container and define rows, columns, and grid template areas.
- Place the grid items in the grid using
grid-row
,grid-column
, andgrid-area
properties. - Use media queries to make your grid layout responsive to different screen sizes.
- Link your CSS file to your HTML file and preview your work in a web browser.