๐ What is grid-template-columns?
grid-template-columns is a core CSS Grid property used to define the number, size, and behavior of columns inside a grid container. It allows you to create fixed-width, flexible, fractional, or responsive columns with clean, powerful syntax.
๐ Basic Usage
Creating 3 Columns
.container {
display: grid;
grid-template-columns: 100px 200px 300px;
}This creates exactly 3 columns with fixed widths.
๐งฑ Column Size Units
| Unit | Description |
|---|---|
| px | Fixed column width |
| % | Percentage of container width |
| fr | Fraction of free space (most powerful) |
| auto | Size based on content |
| minmax() | Define min & max limits |
๐ฅ The fr Unit (Fractional Space)
The fr unit distributes remaining space proportionally.
Fractional Column Layout
grid-template-columns: 1fr 2fr 1fr;
/* Middle column is twice as wide */๐ Using auto
Content-Based Width
grid-template-columns: auto auto 1fr;First 2 columns shrink or grow with content; last column takes leftover space.
๐งฎ Responsive Columns with repeat()
Repeat Syntax
grid-template-columns: repeat(3, 1fr);
/* Same as: 1fr 1fr 1fr */๐ฑ Auto-Fit & Auto-Fill (Responsive Magic)
These automatically generate as many columns as possible based on available width.
Using auto-fit
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));Using auto-fill
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));Note
๐ง minmax() for Flexible Columns
MinMax Behavior
grid-template-columns: minmax(150px, 1fr) 2fr;First column will be at least 150px but can expand up to 1fr.
๐ฆ Combining Units
Mixed Column Types
grid-template-columns: 150px auto 2fr 1fr;You can mix fixed, flexible, and auto columns in one layout.
๐ง Example: Sidebar + Content + Ads Layout
Three-Part Layout
.layout {
display: grid;
grid-template-columns: 250px 1fr 150px;
gap: 20px;
}
๐ Visual Positioning with grid-template-columns
Column count = number of values you provide. Example:
| Value | Total Columns |
|---|---|
| 100px 100px 100px | 3 |
| 1fr 2fr 1fr | 3 |
| repeat(4, auto) | 4 |
๐งฉ Complex Layout Example
Cards Layout
.cards {
display: grid;
gap: 15px;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}Cards will automatically rearrange depending on screen size.
โ ๏ธ Common Mistakes
- Using only 1fr when multiple flexible columns are needed
- Setting fixed px widths for responsive designs
- Using auto incorrectly for equal spacing
- Not using minmax() for stretchable layouts
Note
๐ฅ Summary
grid-template-columns defines the core horizontal structure of a grid. It allows you to create simple or advanced column layouts using fixed units, fractional space, auto sizing, repetition, and responsive patterns.
Official reference:MDN Docs ๐