💄
CSS
Frontend Web DevLanguages
  • Introduction
  • Architecture
    • Default Styles
    • Nesting
    • Layers
  • Page
  • layout
    • Grid
    • Flexbox
    • Container Queries
  • Group 1
    • Pseudo
  • More modern stuff
Powered by GitBook
On this page
  • Guides and Reference
  • Auto-Generate Rows/Columns with Available Space
  • References
  1. layout

Grid

Grids layout your content into columns AND rows. They can be named, auto-generated to available space, and much more. The Parent container controls the size of its child cells.

PreviousPageNextFlexbox

Last updated 1 year ago

Guides and Reference

  • : A straightforward guide.

  • : Left column explains grid parent container properties. The right column explains child container properties.

Auto-Generate Rows/Columns with Available Space

For responsive grids to neatly dump items.

.layout-grid {
    display: grid;
    grid-template-columns: repeat(
      auto-fit,
      minmax(
        /* Minimum column size */
        /* Smaller items (other than text) will resize to fit */
        min(100%, 30ch),
        /* Maximum column size */
        1fr)
    );
  }

auto-fit creates as many columns as can fit given the sizing definition which follows.

minmax() takes the minimum and maximum allowed column size.

Using Stephanie Eckles' explanation (ref at page bottom):

Minimum

We'll calculate it using the math function min(). It returns the smaller computed size between the options.

The reason is that there is potential for overflow once the available space is more narrow than 30ch. By listing 100% as an alternate option, the column can fill whatever space is available below that minimum.

The behavior with this minimum in place means that once the available space becomes less than the amount required for multiple elements to fit in the row, the elements will drop to create new rows. So with a minimum of 30ch, we can fit at least three elements in a 100ch space. However, if that space reduces to 70ch, then only two would fit in one row, and one would drop to a new row.

Maximum

For the maximum, we've used 1fr, which allows the columns to stretch out and share the space equitably when more than the minimum is available.

Customize with Variables

Define grid gap sizes and minimum column sizes as variables, either locally (as shown) or in global styles. The minimum column size variables will function as a "breakpoint" before causing the overflow to become new rows.

.layout-grid {
    --layout-grid-min: 30ch;
    --layout-grid-gap: 3vw;

    display: grid;
    grid-template-columns: repeat(
      auto-fit,
      minmax(min(100%, var(--layout-grid-min)), 1fr)
    );
    gap: var(--layout-grid-gap);
  }

References

Learn CSS Grid
CSS-Tricks Guide
Web.dev Guide
MDN Guide
MDN Reference
Game: CSS Grid Garden
Grid Layout: Modern CSS For Dynamic Component-Based Architecture