CSS Grid Basics: Rows, Columns and Tracks
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
What CSS Grid Is
CSS Grid lays out elements into a two-dimensional structure of rows and columns, defined directly on the container. Unlike Flexbox, which arranges items along one line at a time, Grid lets a design be described as an actual grid up front.
Creating a Basic Grid
.gallery {
display: grid;
grid-template-columns: 200px 200px 200px;
grid-template-rows: 150px 150px;
gap: 16px;
}This creates a grid with three fixed-width columns and two fixed-height rows; any direct children of .gallery automatically become grid items and fill these cells in order.
Rows, Columns and Tracks
Each individual row or column in a grid is called a track. grid-template-columns defines the size of every column track, and grid-template-rows defines every row track - both accept a mix of fixed sizes, percentages, or flexible units.
Using repeat() to Avoid Repetition
.gallery {
display: grid;
grid-template-columns: repeat(3, 200px);
}repeat(3, 200px) is shorthand for writing 200px 200px 200px, and becomes especially useful once column counts grow or need to change based on screen size.
Spacing with gap
.gallery {
gap: 16px; /* row and column gap together */
row-gap: 24px; /* or set them separately */
column-gap: 16px;
}Grid's gap creates spacing purely between tracks, never adding extra space at the outer edges of the grid - a cleaner alternative to margins on individual items.