Equal width columns in CSS Grid
For equal width columns in CSS Grid, employ the repeat()
function with 1fr
units:
This forms a grid with three uniform columns, each taking up one fraction of the container's width. Slightly twist the number to modify the column quantity.
The magic of dynamic columns
To create a fluid column grid where the number doesn't need manual configuration, tap into the power of grid-auto-columns
.
Here, newly inserted columns automatically adjust to share the container width equally. To flexibly regulate the column widths between a set minimum and a maximum, use minmax
:
Notice, each column will be at least 100px wide but could stretch to occupy equal container space.
Unraveling fr units and percent
fr
is your magic wand to flexibly allocate space on the grid. Unlike their percent counterpart, fr
units ignore margins, padding, or borders while calculating space:
Use fr
for easy maintenance of equal column widths despite modifications in the container.
Keeping pace with browsers
Modern browsers are mostly friendly towards CSS Grid. But don't forget to ensure compatibility:
- Watch out for browser version updates
- Employ @supports for those not-so-modern browsers
Keeping it accessible
Make sure your grid layout doesn't leave anyone behind. Remember:
- A clean, semantic HTML foundation
- Testing with screen readers
- Appropriate usage of ARIA roles
CSS Grid vs. Flexbox
CSS Grid shines for 2-dimensional layouts, while Flexbox dominates 1D:
- Flexbox's
flex-grow
also shares space, but not so intuitively for equal width columns - CSS Grid is uncomplicated with its
1fr
simplifying the column equality
See it, believe it!
Explore a practical instance of CSS Grid at play here for a clearer picture:
- CodePen: Dynamic equal width columns example
Lining up columns
For leveling items in a grid, aligning can seem tricky. Here's a cheat code to easily align items on the same row:
Best practices
- Semantic HTML: Clean, valuable HTML is a must
- Plan ahead: Visualize your grid layout before starting
- Embrace responsivity: Employ media queries and responsive units for a fluid layout
Was this article helpful?