grid-template-areas in CSS Grid
What You Learn From This Page
- How grid-template-areas describes named visual regions.
- How quoted rows and repeated names form rectangular areas.
- How Grid items connect to regions with grid-area.
- Why area definitions and track sizing remain separate concerns.
- How to create responsive page, dashboard, documentation, and shop layouts.
- When named areas are clearer than line numbers or named lines.
- Why dynamic lists should normally use auto-placement instead.
- How source order, direct-child rules, and accessibility constrain visual rearrangement.
Introduction
The grid-template-areas property lets an author describe a CSS Grid through named rectangular regions. Instead of translating every page section into numeric row and column lines, the stylesheet can display an area map containing names such as header, navigation, main, and footer. Direct-child Grid items then select those regions through grid-area.
This syntax is especially effective for layouts with known structural roles. A page shell, dashboard, admin interface, documentation view, or editorial composition often has a small set of stable regions whose arrangement changes at responsive breakpoints. An area map makes that arrangement visible in the CSS.
Named areas do not replace track sizing, semantic HTML, or auto-placement. They describe where regions belong, while column and row templates describe how large those regions are. Repeated data such as products and cards is still better handled by an inner auto-placed grid. Understanding those boundaries keeps area templates readable rather than turning them into a manual map of every item.
Basic Syntax
Each quoted string in grid-template-areas represents one Grid row. Space-separated tokens inside that string represent area positions across columns.
.page {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
This template has three area rows and two area columns. The header and footer span both columns because their names repeat in adjacent cells. The middle row contains separate sidebar and main regions.
Assign Items with grid-area
Defining an area map does not automatically associate elements with names. Each participating Grid item receives the corresponding grid-area value.
.site-header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.site-footer { grid-area: footer; }
The values must match the template identifiers. Class names and area names may differ because they serve different roles, but clear naming usually makes the connection easier to follow.
Each String Defines One Row
Three quoted strings create three explicit area rows. Every string must contain the same number of area positions. The whitespace between tokens is only formatting, so authors can align strings for readability without changing the result.
Area rows participate in the explicit grid. Their sizes are not set by the names themselves; they follow grid-template-rows or the normal track-sizing algorithm.
Each Token Defines a Column Position
The number of tokens in one area row establishes the number of area cells across that row. A string containing "sidebar main" describes two positions. All other strings in the same template must also describe two positions.
If an explicit column template is declared, it should correspond to that area structure. A two-token area map paired with three explicit columns is not a coherent three-column region definition.
Repeat Names to Span Columns
Adjacent repeated names merge into one area. The following header occupies all three columns, while the next row retains three distinct regions.
.layout {
display: grid;
grid-template-areas:
"header header header"
"left main right";
}
The header remains one Grid area and one Grid item. Repetition describes its rectangular extent; it does not duplicate the element.
Repeat Names to Span Rows
An area can repeat vertically as well as horizontally. A sidebar appearing in the same column across two consecutive rows spans both row tracks.
.dashboard {
grid-template-areas:
"sidebar header"
"sidebar main";
}
Horizontal and vertical repetition can be combined as long as all cells using one name form a single rectangle.
Named Areas Must Be Rectangular
A named area cannot be L-shaped, disconnected, or otherwise irregular. The cells carrying one name must form one contiguous rectangle. This follows the Grid item model: an item occupies a rectangular area bounded by row and column lines.
If a design appears to require an irregular region, divide it into separate semantic items or redesign the tracks. Attempting to use the same name in an L shape invalidates the area template.
Represent Empty Cells with a Period
A period represents an unnamed empty cell. It allows intentional negative space within the area map.
.editorial {
display: grid;
grid-template-areas:
". title ."
"left main right";
}
Each period is one empty area position. Empty cells can support asymmetric editorial compositions, but ordinary alignment and gaps are often simpler when blank tracks have no structural purpose.
Keep Every Area Row the Same Width
An area template is invalid when one quoted row contains two tokens and another contains three. The map must form a rectangular matrix even when some positions are unnamed periods.
/* Valid three-column template */
grid-template-areas:
"header header header"
"sidebar main aside"
"footer footer footer";
Consistent dimensions let the browser derive one explicit Grid structure from the complete map.
Areas Define Structure, Not Size
The tokens sidebar and main do not imply a 25/75 split or any other dimensions. Track properties define widths and heights independently.
.page {
display: grid;
grid-template-columns: 16rem minmax(0, 1fr);
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
The area map answers where; the row and column templates answer how large. Keeping those questions separate makes responsive layout changes easier to review.
Gaps Remain Separate from Areas
Grid gaps sit between tracks and need no representation in the area strings. A two-column area row remains two tokens even when a large column gap separates them.
.page {
display: grid;
grid-template-columns: 16rem minmax(0, 1fr);
grid-template-areas: "sidebar main";
gap: 2rem;
}
This separation keeps the visual region map focused on placement while spacing stays with the track relationship.
A Complete Page Shell
A common page shell combines semantic regions, stable and flexible columns, and content-aware rows.
.page {
min-height: 100dvh;
display: grid;
grid-template-columns: 16rem minmax(0, 1fr);
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
gap: 1rem;
}
.page-header { grid-area: header; }
.page-sidebar { grid-area: sidebar; }
.page-main { grid-area: main; min-width: 0; }
.page-footer { grid-area: footer; }
The zero minimum on the main item helps wide intrinsic content remain within the flexible track. Responsive rules should stack regions when the sidebar and main content no longer fit comfortably together.
Why Named Areas Are Readable
Numeric line placement is concise but requires knowledge of the template. A rule such as grid-column: 1 / 3 says exactly which boundaries are used, while grid-area: header explains the item's role. For a large structural layout, the named form is often easier to review.
Readability depends on good names. Prefer region responsibilities such as header, filters, navigation, results, or summary. Names such as a, b, left-box, or blue-panel either communicate nothing or become inaccurate when the design changes.
A Dashboard Layout
An application dashboard may keep navigation along the complete left side while placing a top bar above the main region.
.dashboard {
min-height: 100dvh;
display: grid;
grid-template-columns: 15rem minmax(0, 1fr);
grid-template-rows: auto 1fr;
grid-template-areas:
"sidebar topbar"
"sidebar content";
}
The repeated sidebar name creates a two-row rectangle. The inner content region can establish another Grid for widgets without affecting the outer area's naming system.
A Three-Column Page
A wide editorial or reference page may include left navigation, main content, and a right table of contents. The header and footer can span all three positions.
.reference-layout {
display: grid;
grid-template-columns: 14rem minmax(0, 1fr) 14rem;
grid-template-areas:
"header header header"
"left main right"
"footer footer footer";
gap: 2rem;
}
This structure needs a responsive alternative before the side regions compress the article. An area map makes the alternative arrangement explicit.
Mobile-First Responsive Areas
Begin with a simple one-column area sequence that matches the logical source order. Enhance to multiple columns when the component has enough space.
.page {
display: grid;
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
}
@media (min-width: 50rem) {
.page {
grid-template-columns: 16rem minmax(0, 1fr);
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
}
The same Grid items keep their names while the template changes around them. This is one of the property's strongest features.
Visual Order Does Not Change DOM Order
An area template can display the sidebar before main content even when main appears first in the source. Screen readers and keyboard focus generally continue to follow DOM order. A large difference between visual and interaction order can make a page confusing.
Write the HTML in a coherent reading and task sequence. Use areas to create responsive composition without using visual placement as a substitute for semantic source order. Test each layout by keyboard, especially when forms, links, or buttons move visibly.
Area Names Are Custom Identifiers
Area names are author-defined identifiers and do not need to match class names. A .sidebar element can select an area named navigation. The names do need to match between the map and grid-area declaration.
Use consistent lowercase naming and avoid spelling variations. A typo creates a different placement value and may leave the item to auto-place rather than occupy the expected region.
grid-area Is Also a Numeric Shorthand
Besides assigning a named area, grid-area combines four line endpoints in the order row start, column start, row end, column end.
.item {
grid-area: 1 / 2 / 3 / 4;
}
This is equivalent to row lines 1 through 3 and column lines 2 through 4. It is useful for compact precise placement, though separate row and column shorthands can be more readable for teams that might confuse the order with physical box shorthands.
Named Areas Create Named Lines
An area called main generates related main-start and main-end line names. Advanced items can align to those boundaries even when they are not assigned directly to the area.
This means named areas and named lines are connected layers of the same Grid model. Use the area name for ordinary region assignment and the generated lines when a component needs more precise spanning relative to that region.
A Documentation Layout
Documentation commonly combines primary navigation, a readable article track, and an on-page table of contents.
.docs {
display: grid;
grid-template-columns: 16rem minmax(0, 65ch) 14rem;
grid-template-areas: "nav article toc";
gap: 2rem;
}
.docs-nav { grid-area: nav; }
.article { grid-area: article; }
.page-toc { grid-area: toc; }
At smaller widths, secondary regions can stack, move into disclosures, or be omitted according to product requirements. If an item is absent, revise the map when its empty region would waste important space.
An E-Commerce Layout
A shop can assign filters and products to known structural regions while product cards auto-place inside the products region.
.shop {
display: grid;
grid-template-columns: 16rem minmax(0, 1fr);
grid-template-areas: "filters products";
gap: 2rem;
}
.filters { grid-area: filters; }
.products { grid-area: products; }
This separates page structure from the dynamic product list. Naming every product card as an outer area would tightly couple CSS to data and item count.
Use Areas for Structure, Not Data Lists
Named areas work best when the regions are known and meaningful. Header, filters, results, navigation, and footer are stable roles. Product1, product2, and product3 describe data positions that can change through sorting, filtering, or pagination.
Let repeated items auto-place in an inner Grid. Reserve named areas for the outer component architecture. This division keeps templates short and lets applications render any number of records.
Combine Areas and Auto-Placement
A page can use named areas externally and intrinsic track repetition internally.
.main {
grid-area: main;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(15rem, 100%), 1fr));
gap: 1rem;
}
The main element is a Grid item in the outer page and a Grid container for cards. Each layout context has a clear, independent responsibility.
Nested Area Systems
Nested Grid containers may reuse area names because names are local to each Grid formatting context. An outer page can have a main area, while a nested component uses its own main token without creating a cross-grid connection.
That locality supports component isolation. It also means a descendant cannot select an area in an ancestor's map unless it is a direct Grid item participating in that ancestor's grid.
Direct Children Still Matter
Only direct children of a Grid container can be assigned to that container's named areas. If an extra wrapper surrounds the intended sidebar and main elements, the wrapper is the Grid item. Its children cannot independently occupy the outer areas.
Place the wrapper as one region, remove it only when it has no semantic or behavioral role, or establish a nested Grid on it. Nested layout is usually safer than flattening meaningful structure for styling convenience.
Intentional Empty Space
Periods can create asymmetric compositions, but empty cells still occupy tracks whose sizes come from the column and row templates. A blank area therefore consumes space. Ensure the negative space is intentional at every supported width.
For ordinary centering, readable line length, or outer gutters, dedicated flexible tracks may be clearer than an area map full of periods. Use empty area cells when they explain a real regional composition.
Named Areas Versus Line Numbers
| Technique | Best Fit | Strength |
|---|---|---|
| Named areas | Page shells and known semantic regions | Readable visual map |
| Numeric lines | Simple spans and small component grids | Compact precision |
| Named lines | Shared structural boundaries | Precise descriptive coordinates |
| Auto-placement | Repeated dynamic items | Low maintenance |
These techniques are complementary. A page shell can use areas, a full-width message can use 1 / -1, and the card list inside main can auto-place.
When grid-template-areas Is Unnecessary
A simple icon, text, and action row may be fully explained by grid-template-columns: auto 1fr auto. Naming every cell adds vocabulary without improving the relationship. Likewise, a regular gallery needs track definitions and auto-placement, not one name per card.
Use area maps when they make the architecture easier to understand or rearrange. Avoid them when the structure is already obvious from a small track template.
Maintain Area Maps as Contracts
Treat each responsive map as a complete contract among region names, item assignments, and track dimensions. When a region is renamed, update both the container and item declaration. When a column is added, update every quoted row to the new token count and revise sizing.
Keep the area map near its related row and column definitions. Splitting them across distant style layers makes it difficult to see whether the visual matrix and dimensions still agree. Component-level CSS should own the full structural contract when possible.
Optional Regions and Application State
Applications often hide a filter panel, secondary navigation, or utility rail. If the corresponding Grid item is absent but its area remains in the map, the track may still consume space. Provide an alternate template for that state or allow the region to collapse through an appropriate track strategy.
Do not assume an empty item and a missing item behave identically. Test loading, permission, error, and empty states because each can change which direct children participate and whether a structural region remains useful.
How Invalid Area Maps Fail
The browser parses the entire grid-template-areas value as one declaration. If row lengths differ, a repeated name forms a nonrectangular shape, or the syntax is otherwise invalid, the whole property is rejected rather than partially applying the valid-looking rows. The Grid container may still exist and its items may still auto-place, which can make the failure look like missing assignments instead of an invalid template.
Inspect the computed style and browser console or Styles panel when an area map appears to do nothing. A crossed-out declaration, missing computed value, or absent area labels in the Grid overlay usually points to parsing. Formatting each visual row on its own source line makes token counts and rectangular patterns easier to review.
Use a fallback layout that remains readable when advanced placement is unavailable or rejected. Normal source order and block flow provide a good base. The Grid enhancement should improve arrangement without being the only thing that gives the document a meaningful sequence.
Alignment Inside Named Areas
An area identifies the item's available rectangular region, but it does not require the item to fill every pixel. Grid's initial stretch behavior often expands items across their assigned area. Container properties such as justify-items and align-items set defaults, while justify-self, align-self, or place-self can adjust one item.
.hero-layout {
display: grid;
grid-template-areas: "hero";
place-items: center;
}
.hero-content {
grid-area: hero;
place-self: end start;
}
Do not add extra empty area cells merely to achieve alignment that self-alignment or track sizing can express more clearly. Area maps should describe meaningful structural occupancy; alignment properties control where an item sits inside that occupancy.
Area Content Still Controls Intrinsic Size
A named region does not isolate the track system from its content. A long navigation label, wide table, preformatted code block, or intrinsic image can establish a minimum contribution that makes a column wider than expected. Use minmax(0, 1fr) on flexible tracks, min-width: 0 on shrinkable Grid items, and appropriate wrapping or contained scrolling for the actual content.
This is especially important when a mobile and desktop map use the same item in different regions. A table that fits the full-width mobile main area might overflow when desktop main shares space with a sidebar. Test the actual content in every template rather than assuming that a valid area map is automatically responsive.
Rows are also content-aware. A header assigned to an auto row grows when text wraps. Avoid rigid row heights unless clipping or internal scrolling is a deliberate part of the component.
A Worked Responsive Admin Shell
Consider an application with a top bar, navigation, primary workspace, contextual panel, and status footer. The logical source order can begin with header and navigation, followed by main and contextual information, then footer. A single-column base keeps that sequence understandable without Grid.
.admin {
min-height: 100dvh;
display: grid;
grid-template-areas:
"topbar"
"navigation"
"workspace"
"context"
"status";
}
@media (min-width: 48rem) {
.admin {
grid-template-columns: 15rem minmax(0, 1fr);
grid-template-rows: auto 1fr auto;
grid-template-areas:
"navigation topbar"
"navigation workspace"
"navigation status";
}
.admin-context {
display: none;
}
}
@media (min-width: 75rem) {
.admin {
grid-template-columns: 15rem minmax(0, 1fr) 18rem;
grid-template-areas:
"navigation topbar topbar"
"navigation workspace context"
"navigation status status";
}
.admin-context {
display: block;
}
}
This example illustrates why each state needs a complete contract. At medium width the contextual region is removed from the visual shell; at wide width it returns as a dedicated track. In a real application, hiding content may be inappropriate, so the medium treatment could instead use a disclosure, dialog, or position below the workspace.
Switch Templates Based on Component Space
Viewport media queries work for top-level page shells, but reusable components may appear in containers of very different widths. A settings panel can have a wide viewport and still be placed inside a narrow dialog. Container queries allow its area map to respond to the space actually available to that component.
.settings-shell {
container-type: inline-size;
}
.settings {
display: grid;
grid-template-areas:
"navigation"
"content";
}
@container (min-width: 45rem) {
.settings {
grid-template-columns: 14rem minmax(0, 1fr);
grid-template-areas: "navigation content";
}
}
Use container queries when the component boundary is stable and local sizing determines the design. Do not introduce them merely to replace every media query; page-level regions can still respond naturally to the viewport.
Area Names and Design-System Contracts
In a component library, area names can form part of a layout contract. A shell component may promise areas such as header, primary, secondary, and footer, while consumers provide content elements assigned to those roles. Keep the vocabulary small, documented, and based on meaning rather than one visual arrangement.
Avoid exposing dozens of internal names that prevent the component from evolving. The area API should describe meaningful slots. Repeated child content should remain an internal auto-placed collection, and consumers should not depend on private line coordinates unless the system intentionally exposes them.
When names change, treat the update like an interface change. Search all selectors and examples, update responsive templates together, and test states where some slots are absent. Consistent contracts reduce the risk that a valid item name silently stops matching a renamed map.
Progressive Enhancement and Print
Semantic source order makes a useful fallback possible. Define readable block flow first, then establish the area map inside the supported layout context. Modern target browsers support Grid broadly, but this layering still protects content from invalid declarations and simplifies non-screen presentations.
Print often benefits from a different area strategy. Side navigation and interactive filters may be omitted, while main content and references stack into one column. A print rule can replace the screen map and remove unnecessary fixed-height or viewport-based tracks.
@media print {
.page {
display: block;
}
.sidebar,
.interactive-tools {
display: none;
}
}
The exact print treatment depends on content requirements, but it should be deliberate rather than an accidental rendering of the application shell.
Common Mistakes and Corrections
| Mistake | Correction |
|---|---|
| L-shaped or disconnected area | Keep each name as one rectangle |
| Different token counts per row | Use a consistent rectangular matrix |
| Area spelling mismatch | Match grid-area values exactly |
| Expecting names to size tracks | Define grid-template-columns and rows separately |
| Missing item assignment | Add grid-area to the direct Grid item |
| Naming every dynamic card | Use auto-placement for repeated data |
| Applying an outer area to a grandchild | Place its wrapper or create a nested Grid |
| Visual form order differs from DOM | Keep source and interaction order logical |
| Desktop map inherited on mobile | Define a complete mobile-first template |
Debugging grid-template-areas
First confirm that the container computes to display: grid and that the intended item is a direct child. Validate equal token counts and rectangular names. Compare every grid-area value with the map, including capitalization and spelling.
Next inspect responsive rules. A later media query may replace the template or a more specific item rule may override placement. Use the browser's Grid overlay to display area labels, lines, track sizes, and gaps rather than inferring boundaries from content.
1. Confirm display: grid
2. Count every token in every quoted row
3. Check that each named region is rectangular
4. Match item grid-area values exactly
5. Confirm the item is a direct child
6. Inspect row and column sizing
7. Check responsive and overriding rules
8. Display named areas with DevTools
Production Testing
Test every area template at intermediate widths, not only at named breakpoints. Long navigation labels or larger text can make a two-column design unusable earlier than expected. Container queries may be appropriate when a component should respond to its own available width.
Verify keyboard and reading order after each visual rearrangement. Test right-to-left direction, zoom, translations, missing regions, validation messages, and dynamic content. Area maps can make large changes look simple in CSS, but all content still needs enough space and a coherent interaction sequence.
Check printing and downloadable content when the layout is part of those workflows. A print stylesheet may need a simpler single-column area map rather than inheriting the screen shell.
Comparison Summary
| Concept | Purpose |
|---|---|
grid-template-areas | Defines named rectangular regions |
grid-area | Assigns a Grid item to a region |
. | Represents an unnamed empty cell |
| Repeated area name | Spans adjacent cells in one rectangle |
grid-template-columns | Sizes area columns |
grid-template-rows | Sizes area rows |
Common Interview Questions
What does grid-template-areas do? It defines named rectangular regions in a Grid container through a visual string-based map.
How is an item assigned to an area? Give the direct Grid item grid-area: area-name.
What does a period mean? It represents an unnamed empty cell in the area template.
Can an area be L-shaped? No. Each named area must form one contiguous rectangle.
What does repeating an area name mean? The region spans those adjacent cells horizontally, vertically, or both.
Does grid-template-areas define column widths? No. Track sizes are controlled separately.
Can the map change at breakpoints? Yes. Responsive structural rearrangement is one of its strongest use cases.
Must area names match class names? No. Only the template token and the item's grid-area value must match.
When should named areas be preferred? Use them for known structural regions whose visual map improves readability and responsive maintenance.
Practical Review Checklist
- Use meaningful region names based on responsibility.
- Keep every named area rectangular and contiguous.
- Use periods only for intentional empty cells.
- Keep every quoted row at the same token count.
- Define track sizes separately from area placement.
- Assign regions only to direct Grid items.
- Use areas for stable structure and auto-placement for repeated data.
- Begin with a logical mobile source and area order.
- Keep reading, visual, and keyboard order coherent.
- Provide alternate maps for optional-region states when needed.
- Test long text, translations, zoom, RTL, and print output.
- Use the browser Grid overlay to verify labels and tracks.
Key Takeaway
grid-template-areas turns stable Grid regions into a readable visual map. Quoted strings describe rows, tokens describe area cells, repeated names create rectangular spans, and periods create unnamed cells. Direct Grid items connect to those names with grid-area.
Use area maps for meaningful page and component structure, while row and column properties control size and inner grids handle dynamic collections. Keep source order logical, define complete responsive templates, and avoid naming every repeated item. When those boundaries are respected, named areas make sophisticated layouts easier to explain, revise, and debug.