CSS Grid layout basics for WordPress theme developers
For years theme layouts were built with floats or with the Bootstrap 12-column grid. Both work for equal columns, but anything asymmetric means nested rows, offset classes and clearfix hacks. CSS Grid works in two dimensions at once, rows and columns, so one rule on the container describes the whole structure of a section without extra wrappers.
Problem: Multi-column theme layouts built with floats or framework classes need a lot of markup and break at intermediate screen sizes.
Solution: Use CSS Grid for the layout of the page and its sections, and Flexbox for aligning items inside a single row or column.
The building blocks
grid-template-columnsandgrid-template-rowsdefine the tracks: fixed sizes, percentages, thefrunit (a share of the free space) orminmax( min, max );repeat()repeats a track definition, and withauto-fillorauto-fitit creates as many columns as fit;gapsets the space between tracks, without the outer margins and negative-margin tricks of grid frameworks;grid-columnandgrid-rowmake an item span several tracks.
Common theme patterns
/* Post or product grid: as many columns of at least 280px as fit, no media queries */
.posts-grid {
display: grid;
grid-template-columns: repeat( auto-fill, minmax( 280px, 1fr ) );
gap: 2rem;
}
/* Content + sidebar */
.site-content-area {
display: grid;
grid-template-columns: minmax( 0, 1fr ) 300px;
gap: 3rem;
}
/* A full-width hero above two columns */
.page-layout {
display: grid;
grid-template-columns: 1fr 1fr;
}
.page-layout .hero {
grid-column: 1 / -1; /* from the first to the last line */
}
/* Gallery with a bigger featured tile */
.gallery-grid {
display: grid;
grid-template-columns: repeat( 3, 1fr );
grid-auto-rows: 200px;
gap: 1rem;
}
.gallery-grid .featured {
grid-column: span 2;
grid-row: span 2;
}
/* One column on mobile */
@media ( max-width: 768px ) {
.site-content-area,
.page-layout {
grid-template-columns: 1fr;
}
}
The minmax( 0, 1fr ) in the sidebar layout is not a typo: a plain 1fr column cannot become narrower than its content, so a long URL or a wide table in a post would push the sidebar out of the screen.
Centering
To center an item in its cell, use place-items: center on the container or place-self: center on the item: both axes in one property.
NOTE: All current browsers support CSS Grid. Internet Explorer 11 only knows an old version of the specification with the -ms- prefix and without auto-fill and gap, so if it still matters for a project, give it a simple one-column layout with @supports ( display: grid ) around the grid rules.