Mastering CSS Grid Template Areas: A Hands-On Example
CSS Grid Layout is a powerful tool for creating two-dimensional layouts with ease. One of its standout features is the use of template areas, which allow you to name grid areas and place elements into them. Let's dive into a practical example to understand this concept better.
Setting Up the Grid
First, let's set up a simple CSS Grid with three columns and two rows. We'll name the grid areas for better understanding.
```css .container { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: auto 1fr; grid-template-areas: "header header header" "sidebar main aside"; } ```
Understanding the Template Areas
The `grid-template-areas` property takes a string of named grid areas. In our example:

- `header` spans across all three columns.
- `sidebar` and `aside` each occupy one column, with `main` taking up the remaining two columns.
Placing Elements in the Grid
Now, let's place our HTML elements into these named areas.
```html
Using the `grid-area` Property
Each element can be placed into a specific grid area using the `grid-area` property. This property can take a single value, which corresponds to the name of the grid area.
```css header { grid-area: header; } nav { grid-area: sidebar; } main { grid-area: main; } aside { grid-area: aside; } ```
Responsive Design with Media Queries
CSS Grid is responsive by default, but you can also use media queries to adjust your layout at different screen sizes.

```css @media (max-width: 600px) { .container { grid-template-columns: 1fr; grid-template-rows: auto auto 1fr; grid-template-areas: "header" "sidebar" "main" "aside"; } } ```
Comparing Grid and Flexbox
While CSS Grid is great for two-dimensional layouts, Flexbox is better suited for one-dimensional layouts. Here's a comparison of the two:
| CSS Grid | Flexbox |
|---|---|
| Two-dimensional layout | One-dimensional layout |
| Named grid areas | Flex lines |
| Item placement with `grid-area` | Item placement with `order` |
In conclusion, CSS Grid's template areas feature provides a powerful and intuitive way to create complex layouts. By understanding and utilizing this feature, you can build responsive and efficient web designs.





![[css-grid][css-flexbox] Pinterest/Masonry style layout support · Issue #945 · w3c/csswg-drafts](https://i.pinimg.com/originals/07/5c/1f/075c1f175b27b6ef840ee9d7bcff8d40.png)















