Logo
TUTORIAL

Advanced CSS Grid Guide

CSS Grid is a two-dimensional layout system. It allows you to align content into rows and columns simultaneously, giving you total control over the web page structure.

1. Understanding the 'fr' Unit

The fr unit represents a fraction of the free space in the grid container. It is much better than using percentages because it handles gaps automatically.

/* Three columns: first is 200px, others split remaining space */ .container { display: grid; grid-template-columns: 200px 1fr 2fr; }

2. Key Container Properties

Property Description
grid-template-columns Defines column widths (e.g., 1fr 1fr 1fr).
repeat(n, size) Helper function to avoid typing same values (e.g., repeat(3, 1fr)).
place-items Shorthand to center items both vertically & horizontally (e.g., center).
gap Controls the spacing between rows and columns.

3. Responsive Magic: Auto-Fit & MinMax

One of the most powerful features of Grid is creating responsive layouts without media queries. The example below uses auto-fit.

Card 1
Card 2
Card 3
Card 4
/* This will automatically wrap items based on screen size */ .grid-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; }

4. Naming Layout Areas

Using grid-template-areas makes your CSS readable. You can literally "draw" your layout in the code.

Header
Sidebar
Main Content Area
Flexbox vs Grid: Remember, Flexbox is for small components (like a navbar), while Grid is for the whole page layout (header, sidebar, content).

IDE Settings

X