Grid Intro in CSS
? Introduction to CSS Grid
CSS Grid Layout is a powerful two-dimensional layout system for the web. It allows you to create complex layouts by dividing a container into rows and columns, and placing child elements precisely within that grid.
Why Use CSS Grid?
Works in both dimensions: rows and columns.
Makes creating complex and responsive layouts easier.
Provides fine control over alignment, sizing, and spacing.
Allows explicit positioning of elements anywhere on the grid.
Basic Terminology
| Term | Description |
|---|---|
| Grid Container | The element with display: grid or inline-grid — it establishes the grid context. |
| Grid Items | The direct children inside the grid container. |
| Grid Lines | The dividing lines between rows and columns, numbered starting at 1. |
| Grid Tracks | The rows or columns themselves (space between grid lines). |
| Grid Cells | The single unit space between a row and a column line. |
| Grid Areas | Rectangular areas spanning one or more grid cells, can be named. |
How to Start with CSS Grid
1. Define a Grid Container
.container { display: grid;}2. Define Rows and Columns
.container { display: grid; grid-template-columns: 100px 200px 100px; /* 3 columns */ grid-template-rows: 50px 100px; /* 2 rows */}3. Place Grid Items
By default, grid items are placed sequentially in the grid cells.
Simple Example
<div class="container"> <div class="item1">1</div> <div class="item2">2</div> <div class="item3">3</div> <div class="item4">4</div></div>.container { display: grid; grid-template-columns: repeat(2, 150px); grid-template-rows: 100px 100px; gap: 10px;}.container > div { background-color: lightblue; text-align: center; line-height: 100px; font-size: 24px;}This creates a 2x2 grid of equal-sized boxes.
Summary
CSS Grid is for 2D layouts.
Define grid with
display: grid.Set columns & rows with
grid-template-columnsandgrid-template-rows.Control gaps with
gap.Place items automatically or manually.
Want me to show how to position items explicitly or create responsive grids next?