How to Build a Responsive Website with CSS Grid
CSS Grid is the most powerful layout system in CSS. This guide shows you how to build a responsive website layout that works on all screen sizes.
Setting Up a Basic Grid Layout
Define a grid container with display: grid. Use grid-template-columns and grid-template-rows to define the layout. For a responsive blog layout: grid-template-columns: 1fr 300px creates a main content area and sidebar. The 1fr unit distributes available space proportionally.
Auto-Fit and Auto-Fill for Responsive Columns
Use repeat(auto-fit, minmax(300px, 1fr)) to create columns that automatically adjust to the container width. This creates layouts that go from 1 column on mobile to 3-4 columns on desktop without media queries. Auto-fit collapses empty tracks, while auto-fill preserves them.
Using Grid Template Areas
Define named areas with grid-template-areas: "header header" "main sidebar" "footer footer". Assign grid-area names to child elements. Change areas with media queries for different screen sizes. This approach makes layout changes incredibly intuitive.
Media Queries with Grid
Override grid-template-columns and grid-template-areas in media queries. On mobile, switch to a single column layout: grid-template-columns: 1fr and single-row areas. Use min-width breakpoints for progressive enhancement: 768px for tablets, 1024px for desktop.
Gap and Alignment
Use gap (or grid-gap) for consistent spacing between grid items. Use align-items and justify-items for alignment within cells. Use align-content and justify-content for alignment of the entire grid within the container. Gap is now supported in flexbox as well.
Putting It All Together
A complete responsive layout combines: display: grid with auto-fit columns for the main content grid, grid-template-areas for the page-level layout, media queries to switch from desktop to mobile, and gap for consistent spacing. Test on real devices, not just browser DevTools.