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, andauto - 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
frunits for flexible layouts - Mix
pxwithfrfor hybrid designs - Use
repeat()for repetitive layouts (e.g.repeat(3, 1fr)) - Use
grid-template-columnsto control horizontal layout - Use
grid-template-rowsto 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-columnsdefines number and width of columnsgrid-template-rowsdefines number and height of rows- Use
frfor responsive track sizing - Use
auto,min-content, andmax-contentto size based on content - These are core tools for designing grid-based page layouts
Advertisement Slot 1
Advertisement Slot 2