Explain Codes LogoExplain Codes Logo

How can I target a specific column or row in a CSS grid layout?

html
css-grid
responsive-design
accessibility
Nikita BarsukovbyNikita Barsukov·Aug 20, 2024
TLDR

Use grid-column and grid-row properties to pin down specific cells. The format start/end determines the span:

.item { grid-column: 2 / span 2; /* Spans across 2 columns from the 2nd column */ grid-row: 1 / span 2; /* Spans across 2 rows from the first row */ }

Above, .item has been instructed to occupy a 2x2 square. Starting coordinate is 2nd column and 1st row, likewise in the board game Battleship! 🚢

Detailed grid targeting

A. Row targeting: every third

To assign an individual row utilise grid-auto-rows alongside :nth-child:

.grid-container > *:nth-child(3n) { grid-row: 3; /* Move every third item into the third row like a well-behaved child */ }

B. Column targeting: first column

For column selection, cleverly combine grid-template-columns and nth-child:

/* Provided a three-column grid layout */ .grid-container > *:nth-child(3n+1) { background-color: deepskyblue; /* Color me impressed, first column! */ }

CSS isn't the Magic School Bus of your childhood—it can't make column-specific CSS selections. So, we trick it by mentioning 3n+1, singling out the first column of a three-column grid.

C. Targeting special cases

What if the matrix is to have reversed order columns or requires simultaneous row and column items? Properties are not wizards or clones—they can't be everywhere at once. The structure of your HTML must mirror your desired selection.

Grid adaptations breakdown

I. Responsiveness and Media Queries

Adaptability to resize is often commanded by media queries, defining how grid items should behave at different viewport sizes:

@media (max-width: 768px) { .item { grid-column: 1 / -1; /* Going full width, because mobile screens need love too ♡ */ } }

II. Subgrids on standby

A new feature proposed in CSS Grid Level 2 called Subgrids will permit a grid-within-a-grid layout, opening up more complex grid item selection:

.item { display: grid; grid-template-rows: subgrid; /* Let's go Inception on grids! */ }

Optimization methods

Manage clutter with custom properties

Custom properties can dry out a clammy code:

:root { --target-column: 2; /* Define once, use many times. Recycling for the win! */ } .grid-container > *:nth-child(var(--target-column)n) { color: crimson; /* An oasis in the desert of sameness */ }

Accessibility reminder

Ensure your aesthetically pleasing grid changes do not negatively impact screen readers. Accessibility matters too!

The CSS Grid road ahead

Future CSS drafts and standards evolution hint at direct column targeting and additional powerful features like :nth-col() coming soon.