I want an option to collapse CSS grid gaps when grid areas are empty

Submitted by Nick Gard

This idea is currently being discussed.

I want a CSS property — something like gap-collapse — that allows grid gaps to be omitted automatically for rows or columns whose grid areas are entirely empty, so that spacing only appears between content that actually exists.

CSS Grid makes it easy to define named template areas and assign items to them. But when some template areas are conditionally empty — for example because certain optional UI elements are not rendered — the gap between those areas is still reserved, leaving visible blank space where no content exists.

Consider a card layout defined with grid-template-areas that includes a header, a body, an optional action area, and a close button. If no action buttons are rendered, a gap still appears between the body and the close button because the CSS has no way to know the slot is empty:

.card {
display: grid;
gap: 1em;
grid-template-areas:
"header"
"body"
"actions"
"close";
}

If the actions area has no children, the 1em gap above and below it remains, pushing the close button away from the body unnecessarily.

A gap-collapse property with values like none, row, column, or both would mirror the intuition behind margin collapsing in block layout: gaps that border an empty track would collapse to zero, and space would only be inserted between tracks that have actual content.

This would make dynamic, data-driven grid layouts significantly easier to author without needing JavaScript to toggle gap-related classes based on slot occupancy.

Tagged
CSS
Votes
0
What are votes for and how are they tallied?