Back to course

Lesson 70: Placing Items by Grid Area Names

CSS Mastery: From Zero to Hero in 100 Lessons

70. Placing Items by Grid Area Names

Placing items using line numbers is effective but can become confusing in complex layouts. Placing items using named areas is often preferred for readability and maintenance.

Step 1: Defining the Grid Areas

Use grid-template-areas on the container. Each string defines a row, and the names within the string define the columns. Identical names define a single, merged area.

css .page-layout { display: grid; grid-template-columns: 1fr 3fr 1fr; /* Defines 3 columns */

grid-template-areas: "header header header" "nav main aside" "footer footer footer"; }

  • The first row is entirely the header area.
  • The second row has three distinct areas: nav, main, and aside.

Step 2: Assigning Items to Areas

Use the grid-area property on the grid items to assign them to a defined area name.

css header { grid-area: header; }

main { grid-area: main; }

/* The item will automatically take the rows and columns defined by the named area */

Note: Use a dot (.) in the grid-template-areas definition to explicitly leave a grid cell empty.