Deepali's Blog

CSS Grid Layout: A Complete Guide

S

Sarah Johnson

November 25, 2023

CSS Grid Layout: A Complete Guide

CSS Grid Layout: A Complete Guide

CSS Grid Layout is a powerful two-dimensional layout system designed for the web. It allows you to create complex responsive web layouts with ease.

Basic Concepts

CSS Grid Layout introduces a grid-based layout system, with rows and columns, making it easier to design web pages without having to use floats and positioning.

Setting up a Grid

To create a grid container, you set the display property to 'grid' or 'inline-grid':

.container {

display: grid;

grid-template-columns: 1fr 1fr 1fr;

grid-template-rows: 100px 200px;

gap: 20px;

}

This creates a grid with 3 columns of equal width and 2 rows with specific heights, with 20px gaps between cells.

Grid Properties

For the Container

- grid-template-columns: Defines the columns of the grid

- grid-template-rows: Defines the rows of the grid

- gap: Sets the gap between rows and columns

- justify-items: Aligns grid items along the row axis

- align-items: Aligns grid items along the column axis

For the Items

- grid-column: Specifies which column(s) the item will span

- grid-row: Specifies which row(s) the item will span

- justify-self: Overrides the container's justify-items for specific items

- align-self: Overrides the container's align-items for specific items

The fr Unit

The 'fr' unit represents a fraction of the available space:

.container {

display: grid;

grid-template-columns: 1fr 2fr 1fr;

}

This creates three columns where the middle one is twice as wide as the others.

Grid Areas

You can name grid areas and place items in them:

.container {

display: grid;

grid-template-areas:

"header header header"

"sidebar content content"

"footer footer footer";

}

.header { grid-area: header; }

.sidebar { grid-area: sidebar; }

.content { grid-area: content; }

.footer { grid-area: footer; }

Responsive Grids

CSS Grid works beautifully with media queries for responsive designs:

.container {

display: grid;

grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));

gap: 20px;

}

This creates as many columns as can fit with a minimum width of 200px.

Browser Support

CSS Grid is supported in all modern browsers, making it a reliable choice for modern web development.

By mastering CSS Grid, you'll be able to create complex layouts that were previously difficult or impossible with traditional CSS techniques.