grid-template

Definition

The grid-template CSS property is a shorthand property that combines both grid-template-rows and grid-template-columns properties. It is used in grid layouts to define the structure, size, and number of rows and columns in a grid container.

The grid-template property accepts values that specify the size and number of rows and columns. You can define the rows and columns using length values, fractional units (fr), the auto keyword, or the minmax() function.

Here’s an example:

.grid-container {
  display: grid;
  grid-template: 100px 1fr / 1fr 2fr 1fr;
}

In this example, the grid-template property sets up a grid layout with three rows and three columns. The rows are defined as 100px for the first row, and the remaining space is divided evenly (1fr) for the second row. The columns are defined as 1fr, 2fr, and 1fr, respectively.

Using grid-template, you can create flexible and responsive grid layouts, defining the structure and sizing of both rows and columns in a concise way. It allows for the creation of versatile grid structures that adapt to different screen sizes and content requirements.

Syntax

.dashboard {
  display: grid;
  grid-template: "nav nav" auto
                   "sidebar main" 1fr
                   / 18rem 1fr;
}

Values

  • grid-template: <rows> / <columns> shorthand optionally including named areas.
  • Combines grid-template-rows, grid-template-columns, and grid-template-areas.

Practical Examples

.dashboard {
  display: grid;
  grid-template: "nav nav" auto
                   "sidebar main" 1fr
                   / 18rem 1fr;
  gap: 1.5rem;
}

Define rows, columns, and named areas in a single declaration.

HTML
Navigation
Main content
Code
<div class="grid gap-4 rounded-2xl border border-slate-200 bg-white p-4 shadow-sm" style="display:grid; grid-template:'nav nav' auto 'sidebar main' 1fr / 18rem 1fr; gap:1rem;">
  <header class="rounded-lg bg-slate-900/90 p-4 text-sm font-semibold text-white" style="grid-area: nav;">Navigation</header>
  <aside class="rounded-lg bg-slate-100 p-4 text-sm text-slate-700" style="grid-area: sidebar;">Sidebar</aside>
  <main class="rounded-lg bg-slate-50 p-4 text-sm text-slate-700" style="grid-area: main;">Main content</main>
</div>

Tips & Best Practices

  • Named areas make responsive layout changes easier to manage.
  • Use whitespace aligned grid templates for readability.

Accessibility & UX Notes

Maintain logical DOM order even when areas shift positions.

Browser Support

Supported by all evergreen browsers.

  • grid shorthand
  • grid-template-columns
  • grid-template-areas.