CSS Grid Layout is the most robust layout system available in CSS today. It's a 2-dimensional system, meaning it can manage both columns and rows concurrently. In contrast, Flexbox is a 1-dimensional system, focusing primarily on either a single row or column.
In this guide, we will explore the core concepts of CSS Grid and build a fully responsive grid system that adapts perfectly to desktop, tablet, and mobile screens without writing a single CSS media query.
The Container vs. The Items
To initialize a grid, you define a container element with display: grid. All direct children of this container automatically become grid items.
/* Initialize the grid */
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1.5rem;
}
In the snippet above, we use the repeat() helper function along with the fractional unit (1fr) to define three equal-width columns. The gap property sets spacing between the rows and columns.
Responsive Grid Without Media Queries
Writing media queries for every device size can quickly become tedious and verbose. Fortunately, CSS Grid introduces two powerful keywords: auto-fit and minmax().
By combining them, you can tell the browser: "Create as many columns as possible that are at least 250px wide, and expand them to fill the remaining space if there is extra room."
/* Responsive column layout without media queries */
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
}
Here is how the browser calculates this dynamically:
- On a mobile phone (width ~360px), only 1 column fits, which expands to fill the full screen width.
- On a tablet (width ~768px), 2 or 3 columns render side-by-side depending on side padding.
- On a large desktop screen, it can stretch to display 4, 5, or more columns.
By letting the browser handle column rendering math, you eliminate code duplication and create layouts that behave smoothly across all screen sizes.
Summary of CSS Grid Terms
To help you memorize, here is a quick breakdown of key terms:
- Grid Line: The dividing lines that make up the structure of the grid. They can be vertical or horizontal.
- Grid Track: The space between two adjacent grid lines. Essentially, a column or a row.
- Grid Cell: The space between four intersecting grid lines. The smallest unit on a grid.
- Grid Area: The total space enclosed by four grid lines. Can contain any number of grid cells.
By mastering these properties, you can design stunning galleries, dashboards, and landing pages with minimal stylesheet overhead. Try copying the responsive grid snippet into your project and see it in action!