Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my grid ignore grid-gap if an area is empty?

Tags:

css

css-grid

I have a simple grid layout with a grid-gap and defined grid-areas. However not all areas have content all the time. If an area doesn't have content, I don't want there to be a double the gap in between the items. Is there a way to ignore the gap on empty areas, without using a different grid-template, to ignore the double gap between items?

Example:

.grid {
  display: grid;
  grid-template-areas: "area-1" "empty-area" "area-3" "area-4";
  grid-template-columns: auto;
  grid-gap: 20px;
}

.area-1 {
  grid-area: area-1;
  background: red;
}

.area-3 {
  grid-area: area-3;
  background: green;
}

.area-4 {
  grid-area: area-4;
  background: blue;
}
<div class="grid">
  <div class="area-1">Hello</div>
  <!-- empty area is missing -->
  <div class="area-3">World</div>
  <div class="area-4">!</div>
</div>
like image 510
Stefan Avatar asked Nov 18 '25 12:11

Stefan


1 Answers

In short: No. You can't ignore the gap when predefining the grid areas like this.

What best fit the snippet you've provided is using grid-template-rows property instead of grid-template-areas

.grid {
  display: grid;
  grid-template-rows: repeat(auto-fit, 1.2rem);
  grid-gap: 20px;
}

.area-1 {
  background: red;
}

.area-3 {
  background: green;
}

.area-4 {
  background: blue;
}
<div class="grid">
  <div class="area-1">Hello</div>
  <!-- empty area is missing -->
  <div class="area-3">World</div>
  <div class="area-4">!</div>
</div>
like image 101
Ravid Avatar answered Nov 20 '25 03:11

Ravid