CSS Grid Layout

CSS Grid Layout is the most powerful layout system available in CSS. It is a 2-dimensional system, meaning it can handle both columns and rows at the same time, unlike Flexbox which is largely 1-dimensional.

CSS Grid Layout

1. Important Terminology

Before diving into code, you must understand the "parts" of a grid:

  • Grid Container: The element on which `display: grid` is applied.
  • Grid Item: The direct children of the container.
  • Grid Line: The dividing lines that make up the structure (vertical and horizontal).
  • Grid Cell: The smallest unit of the grid (like a single cell in Excel).

2. Defining the Grid

To start, you define how many columns and rows you want using the container properties:

.container {
    display: grid;
    grid-template-columns: 200px 200px 200px;
    grid-template-rows: auto;
    gap: 20px;
}

3. The 'fr' Unit

CSS Grid introduced the fr unit (fractional unit). It represents a fraction of the free space in the grid container. Using `1fr 2fr 1fr` would split the space into 4 parts, giving the middle column twice as much space as the others.

Knowledge Check

1. CSS Grid is primarily known as a ______ system.
A) 1-Dimensional | B) 2-Dimensional | C) 3-Dimensional

2. Which property is used to create space between grid items?
A) spacing | B) padding | C) gap

3. What does 1fr represent?
A) 1 fixed pixel | B) 1 fraction of available space | C) 1% of the width