SmartCodingTips

Grid Template Areas in CSS

The grid-template-areas property allows you to define named layout sections visually, making your grid structure more readable and easier to maintain.

1. Basic Syntax

Define grid layout areas using quoted strings for each row:


.container {
    display: grid;
    grid-template-areas:
        "header header"
        "sidebar main"
        "footer footer";
    grid-template-columns: 200px 1fr;
    grid-template-rows: auto 1fr auto;
}
            

Then, assign areas to items:


.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }
            

2. Visual Representation

The layout above corresponds to:

+----------------------+--------------------+
|       header         |      header        |
+----------------------+--------------------+
|      sidebar         |       main         |
+----------------------+--------------------+
|       footer         |      footer        |
+----------------------+--------------------+
            

3. Empty Grid Cells

Use a period (.) to represent an empty cell:


grid-template-areas:
    "header header"
    ".      main"
    "footer footer";
            

4. Tips & Best Practices

  • Area names must be valid identifiers (no spaces or special characters).
  • Keep the grid layout visually structured like ASCII art.
  • Always ensure each string row has the same number of columns.

Conclusion

grid-template-areas makes grid layouts more intuitive and maintainable. It's especially useful for larger layouts and semantic structuring.