Creating a Grid Layout

While CSS Grid is great for simple rows and columns, its true power lies in mapping out entire webpage layouts. Using the grid-template-areas property, you can visually design your layout directly in your CSS.

A classic website layout usually consists of a header at the top, a navigation sidebar on the left, a main content area in the middle, a secondary sidebar on the right, and a footer at the bottom.

Naming the Grid Areas

To start, you must assign a grid-area name to each section of your HTML:

This allows the grid container to recognize and place them in the layout.

Defining the Grid Layout

Next, we apply display: grid to the parent container. The grid-template-areas property lets us draw our layout using the names we just assigned. Each string represents a row, and each word inside represents a column slot:

In the example above, the "header" takes up all four columns of the first row. The "nav" gets one column, "main" gets two columns, and "sidebar" gets one column in the second row. Finally, the "footer" takes up all four columns of the third row.

Making it Responsive

The best part about this method is how easy it is to make responsive. Using a media query for mobile screens, we can simply redefine the grid-template-areas string to force everything into a single column:

You can add more breakpoints to the media query to make the layout responsive for tablets, larger phones, and desktops. In this example we use 576px as the breakpoint to make the layout responsive for mobile phones. However, you can change this value to whatever you need it to be. A common breakpoint for tablets is 768px and a common breakpoint for desktops is 1024px.

Full Working Example

Below is a fully styled implementation. Resize your browser window to watch the complex multi-column layout instantly snap into a perfect, mobile-friendly vertical stack:

View Output Full Screen Preview

The above example uses a breakpoint of 576px so that you see the full effect when viewing in the (narrow) editor/preview window (after clicking the button to view the example). As mentioned, you can change this value to whatever you need it to be.