Grid wrapper

The grid wrapper pattern is useful for aligning grid content within a central wrapper while also allowing items to break out and align to the edge of the containing element or page.

Requirements

Items placed on the grid should be able to align to a horizontally-centered max-width wrapper or the outer edges of the grid, or both.

Recipe

Choices made

This recipe uses the CSS grid minmax() function to define the grid track sizes in the grid-template-columns property. For the central columns with a maximum width, we can set a minimum value of 0 or greater and a maximum value that specifies the maximum size the column tracks will grow to. Using relative or absolute <length> units (pixels, ems, rems) will create a fixed maximum size for the central wrapper, whereas using <percentage> values or viewport units will cause the wrapper to grow or shrink in response to its context.

The outer two columns have a maximum size of 1fr, meaning that they will each expand to fill the remaining available space in the grid container.

Useful fallbacks or alternative methods

To center the grid horizontally on the page you can set a max-width along with left and right auto margins:

css
.grid {
  max-width: 96vw; /* Limits the width to 96% of the width of the viewport */
  margin: 0 auto; /* horizontally centers the container */
}

Accessibility concerns

Although CSS grid enables positioning items anywhere (within reason), ensuring that your underlying markup follows a logical order is important (see CSS grid layout and accessibility for more details).

See also