0
0
CssHow-ToBeginner · 4 min read

How to Use grid-template-columns in CSS for Layouts

Use grid-template-columns in CSS to define the number and width of columns in a grid container. You specify column sizes using units like fr, px, or percentages inside the property. This controls how space is divided horizontally in a grid layout.
📐

Syntax

The grid-template-columns property sets the width of each column in a CSS grid container. You list column sizes separated by spaces.

  • auto: size based on content
  • fr: fraction of available space
  • px, em, %: fixed or relative sizes
  • repeat(): shorthand to repeat columns
css
grid-template-columns: 100px 1fr 2fr;
💻

Example

This example creates a grid with three columns: the first is 100 pixels wide, the second takes one fraction of remaining space, and the third takes two fractions. The grid items fill these columns horizontally.

css
html, body {
  height: 100%;
  margin: 0;
}
.container {
  display: grid;
  grid-template-columns: 100px 1fr 2fr;
  gap: 10px;
  height: 100vh;
  padding: 10px;
}
.item {
  background-color: #4CAF50;
  color: white;
  padding: 20px;
  font-size: 1.2rem;
  text-align: center;
}
Output
<div class="container"> <div class="item">Column 1 (100px)</div> <div class="item">Column 2 (1fr)</div> <div class="item">Column 3 (2fr)</div> </div>
⚠️

Common Pitfalls

Common mistakes include:

  • Using fixed widths for all columns, which can break responsiveness.
  • Forgetting to set display: grid; on the container.
  • Misunderstanding fr units as fixed sizes instead of flexible fractions.
  • Not using repeat() for repeating columns, which makes code longer.
css
/* Wrong: no grid display set */
.container {
  grid-template-columns: 1fr 1fr 1fr;
}

/* Right: grid display added */
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}
📊

Quick Reference

ValueMeaningExample
autoColumn width fits contentgrid-template-columns: auto auto auto;
frFraction of free spacegrid-template-columns: 1fr 2fr;
px, em, %Fixed or relative sizegrid-template-columns: 100px 20%;
repeat()Repeat columns easilygrid-template-columns: repeat(3, 1fr);

Key Takeaways

Always set display: grid; on the container before using grid-template-columns.
grid-template-columns defines the number and width of columns in a grid layout.
Use flexible units like fr for responsive column widths.
The repeat() function helps simplify repeating column patterns.
Avoid fixed widths for all columns to keep layouts adaptable on different screens.