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

1

18

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>
Plenipotent answered 17/11, 2020 at 10:16 Comment(4)
don't use gap, use bottom margin applied to elements (excluding the last one)Tokoloshe
Did for mnow, but really hoped I could do all my spacings with gaps, to be consitant.Plenipotent
by the way you don't really need to use area if you will only have 1 column, remove the template-areas and everything will be fine (the element will get placed automatically)Tokoloshe
As far as I know, it is not possible using grid-gap. If your goal is to have a flexible layout, CSS offers flexbox (as the name describes). A "flexible" grid could work but was not made for that purpose and your project will be always open to layout errorsBroke
O
1

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>
Overlay answered 4/1, 2023 at 20:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.