How to Build a Responsive Website Using CSS Grid: A Step-by-Step Tutorial

CSS Grid is a powerful layout system that makes responsive web design intuitive and efficient. Unlike older methods, Grid handles both columns and rows simultaneously, letting you create complex layouts with minimal code. In this tutorial, you’ll learn the core techniques to build a flexible, mobile-friendly site.

Article illustration

1. Setting Up the Basic Grid Container

Start by defining a grid container on your parent element. Use display: grid and set columns with grid-template-columns. For responsiveness, avoid fixed pixel values and use fractional units (fr) or auto.

  • grid-template-columns: repeat(3, 1fr); creates three equal columns.
  • Add gap: 20px; to space items evenly.

2. Making Columns Responsive with auto-fit and minmax

To let columns wrap automatically based on screen width, use auto-fit combined with minmax(). This eliminates media queries for simple cases.

  • grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  • Each grid item will be at least 250px wide and expand to fill space.
  • On narrow screens, items stack into a single column.

3. Controlling Row Heights and Placement

Use grid-auto-rows to set consistent row heights, or minmax() for flexible ones. For precise placement, assign grid-column and grid-row to individual items, but keep most items automatic for simplicity.

  • grid-auto-rows: minmax(100px, auto); ensures rows are at least 100px tall.
  • Header and footer can span full width by setting grid-column: 1 / -1;.

4. Adding Responsive Tweaks with Media Queries

While Grid handles many breakpoints automatically, you may need media queries for major layout shifts (e.g., sidebar on desktop, hidden on mobile).

  • Example: @media (max-width: 600px) { .container { grid-template-columns: 1fr; } }
  • Change column counts or gap sizes as needed.

Conclusion

CSS Grid gives you a clean, declarative way to build responsive layouts without frameworks. Start with a container, use auto-fit and minmax, then add media queries only for special cases. Your site will adapt smoothly to any screen size.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *