Explain Codes LogoExplain Codes Logo

How do I specify row heights in CSS Grid layout?

html
responsive-design
css-grid
layout
Anton ShumikhinbyAnton Shumikhin·Feb 13, 2025
TLDR

Set CSS Grid row heights using grid-template-rows and the following units: px, %, vh, or fr for fluid sizing. Here's an example of fixed-height rows:

.grid-container { display: grid; grid-template-rows: 50px 100px; // Because love comes in all shapes and sizes. }

For flexible, equal-height rows that utilize available space, go for fr units:

.grid-container { display: grid; grid-template-rows: 1fr 1fr; // Sharing is caring! }

1fr represents one fraction of the free space, allowing each row to expand or contract dynamically.

Advanced Techniques for Row Height Control

Precise row height specification

In situations where size consistency is a must, px offers the precision you need:

grid-template-rows: 100px 250px; /* Because 250px > 100px. In pixels we trust! */

For layouts that need proportional sizing, go for the % units:

grid-template-rows: 25% 75%; /* Now that's what I call a 75-25 split! */

Building responsive rows using calc() and min-height

Use calc() to combine units and create dynamic row heights that adapt to viewport changes:

grid-template-rows: calc(50vh - 20px) auto; /* Because magic lies in responsiveness */

min-height can help ensure rows don't disappear when they're empty:

.grid-item { min-height: 100px; /* Let's keep things visible, shall we? */ }

Establishing gaps and column sizes

Employ grid-gap to create visual harmony between rows and columns:

.grid-container { grid-gap: 20px; /* Spacing keeps us sane */ }

To enact a structured layout, define your columns alongside rows:

.grid-container { grid-template-columns: 1fr 2fr 1fr; /* Columns need love too, you know */ }

Advanced Layout Adjustments

Tailoring rows with custom properties

Maintain a coherent layout by sneaking in CSS variables:

:root { --row-height: 150px; /* Variable defined, pass the popcorn! */ } .grid-container { grid-template-rows: var(--row-height) auto; /* Variable applied. Voila! */ }

Spot-on item styling

In the case you need to style a lone ranger, use the :nth-child selector:

.grid-container > div:nth-child(2) { align-self: start; /* Second child just hates conformity */ }

The power of repeat()

Simplify row pattern creation with repeat():

grid-template-rows: repeat(3, 1fr); /* Repeat after me: 1fr, 1fr, 1fr */

Cross-platform harmony

When creating Electron apps, remember that Electron's Chrome version determines your CSS feature coverage.