Course contentsShow
← Web Development
Lesson 370 of 2,9826. CSS GridFree lesson

Centered Layouts with Grid

Center content horizontally and vertically using Grid's alignment properties.

Centered Layouts with Grid

You'll learn how to perfectly center content both horizontally and vertically using CSS Grid's alignment properties.

The Core Idea

CSS Grid makes centering incredibly simple. While Flexbox is great for one-dimensional centering, Grid excels when you want to center content in both directions simultaneously. You use alignment properties on the grid container to position items within their grid cells.

How It Works

Grid provides two main alignment properties:

  • justify-items — aligns items horizontally (along the row/inline axis)
  • align-items — aligns items vertically (along the column/block axis)

Both accept values like start, end, center, and stretch. For perfect centering, set both to center:

.container {
  display: grid;
  justify-items: center; /* center horizontally */
  align-items: center;   /* center vertically */
  height: 100vh;         /* full viewport height */
}

This centers all grid items within their respective grid cells.

The place-items Shorthand

Grid offers a convenient shorthand that combines both properties:

.container {
  display: grid;
  place-items: center; /* centers both axes at once */
  height: 100vh;
}

Think of place-items: center as the "magic centering command" for Grid.

Real-World Example

Creating a classic login box centered on the page:

body {
  display: grid;
  place-items: center;
  min-height: 100vh;
  margin: 0;
}

The content inside your <body> is now perfectly centered both horizontally and vertically, regardless of viewport size.

Key Takeaway: Use place-items: center on a grid container to center its children in both dimensions—Grid's simplest and most elegant centering solution.