In this tutorial, we aim to understand how to use Grid Template Areas effectively for a clean, organized, and readable layout in CSS grid. The CSS grid layout is a two-dimensional layout system that gives you control over items in rows as well as columns, unlike Flexbox which is largely a one-dimensional system.
What will you learn?
- Naming grid areas
- Placing items in these areas
- Creating complex layouts with ease.
Prerequisites
Basic knowledge of HTML and CSS is required for this tutorial.
Grid Template Areas allow us to create a template of our page layout and then place items into this layout. The areas are defined with the grid-template-areas
property.
We can assign names to different grid areas and then use these names to place our items. This makes our layout code more readable and easier to understand.
Below is a simple example of how to use grid template areas:
Example:
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: auto;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
}
In this example, we are defining a grid with three columns of equal size and auto rows. We then assign areas to the grid cells. The header
, main
, and footer
each span across all three columns, while the sidebar
only spans the first column of the second row.
Example 1: Basic Layout
<div class="container">
<div class="item1">Header</div>
<div class="item2">Sidebar</div>
<div class="item3">Main</div>
<div class="item4">Footer</div>
</div>
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: auto;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
}
.item1 { grid-area: header; }
.item2 { grid-area: sidebar; }
.item3 { grid-area: main; }
.item4 { grid-area: footer; }
In this example, we've assigned each div to a grid area using the grid-area
property.
In this tutorial, we've learned how to use Grid Template Areas to create a clean, organized, and readable layout. We explored how to name grid areas and how to place items in these areas.
For more advanced layouts, you can explore nested grids and other CSS grid properties.
Exercise 1:
Create a basic layout for a blog post with a header, main content, sidebar, and footer.
Exercise 2:
Create a photo gallery layout with different sized photos. Some photos should span multiple columns or rows.
Solutions
1. This is similar to the example given above, but you need to adjust the grid-template-areas
and grid-area
properties to fit your content.
2. This is a bit more complex. You will need to assign different grid-area
and span
values to your images to make them span multiple columns or rows.
Remember, practice is key in mastering CSS Grid. Keep experimenting with different layouts and properties.