How can I target a specific column or row in a CSS grid layout?
Use grid-column and grid-row properties to pin down specific cells. The format start/end
determines the span:
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
:
B. Column targeting: first column
For column selection, cleverly combine grid-template-columns and nth-child:
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:
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:
Optimization methods
Manage clutter with custom properties
Custom properties can dry out a clammy code:
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.
Was this article helpful?