CSS Grid grid-template-columns and grid-template-rows

Subject: css

CSS Grid grid-template-columns and grid-template-rows

The properties grid-template-columns and grid-template-rows are fundamental to defining the structure of a CSS Grid layout. They specify how many columns and rows the grid will have, and how big each of them should be.


Why Use These Properties?

  • Create flexible, responsive layouts with precise control
  • Define the exact width of each column and height of each row
  • Use units like px, %, fr, and auto
  • Combine fixed and flexible tracks for hybrid layouts

Syntax

  • Units: px, em, %, fr, auto, min-content, max-content, etc.

Example: 3 Columns & 2 Rows


Explanation

  • grid-template-columns: 200px 1fr 2fr;

    • First column is fixed at 200px
    • Second column takes 1 fraction of remaining space
    • Third column takes 2 fractions (twice as wide as second)
  • grid-template-rows: 100px 150px;

    • First row is 100px tall
    • Second row is 150px tall

Best Practices

  • Use fr units for flexible layouts
  • Mix px with fr for hybrid designs
  • Use repeat() for repetitive layouts (e.g. repeat(3, 1fr))
  • Use grid-template-columns to control horizontal layout
  • Use grid-template-rows to control vertical layout

Common Use Cases

  • Multi-column site layouts (e.g., sidebar, content, ad section)
  • Image galleries and cards
  • Dashboard grid systems
  • Forms with fixed label widths and variable input fields

Key Takeaways

  • grid-template-columns defines number and width of columns
  • grid-template-rows defines number and height of rows
  • Use fr for responsive track sizing
  • Use auto, min-content, and max-content to size based on content
  • These are core tools for designing grid-based page layouts