Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't reserve space in a CSS Grid if the element doesn't exist / is optional

Tags:

html

css

css-grid

I'm using grid-template to set up a simple grid structure for one row and four columns. The two leftmost columns have a fixed width, and the remaining two should fill the remaining space.

However, the second column is optional - it may not be present at all. In this case I do not want to reserve any space for it. The two rightmost columns should fill the space.

This is obviously not possible with grid-template. Is it possible at all?

.grid {
  display: grid;
  grid-template-areas: "one two three four";
  grid-template-columns: 8rem 8rem 1fr 1fr;
}

.one   { background: #404788aa; grid-area: one;   }
.two   { background: #287d8eaa; grid-area: two;   }
.three { background: #3cbb75aa; grid-area: three; }
.four  { background: #dce319aa; grid-area: four;  }
<div class="grid">
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
</div>
<hr><p>Three and Four should fill the space:</p>
<div class="grid">
  <div class="one">One</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
</div>
like image 378
snazzybouche Avatar asked Sep 13 '25 03:09

snazzybouche


2 Answers

Try using display: flex with flex attributes like this:

.flex {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.one   { background: #404788aa; flex: 0 1 8rem; }
.two   { background: #287d8eaa; flex: 0 1 8rem; }
.three { background: #3cbb75aa; flex: 1 1 auto; }
.four  { background: #dce319aa; flex: 1 1 auto; }
<div class="flex">
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
</div>
<hr><p>Three and Four should fill the space:</p>
<div class="flex">
  <div class="one">One</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
</div>
like image 148
ng-hobby Avatar answered Sep 15 '25 21:09

ng-hobby


Flex is probably a better idea, but it is also quite possible to do it easily with the grid. This solution is based on fact that min-content will set second column width to 0, since there is no item there.

.grid {
  display: grid;
  grid-auto-columns: min-content min-content auto auto;
}

.one   { background: #404788aa; width: 8rem }
.two   { background: #287d8eaa; width: 8rem }
.three { background: #3cbb75aa; grid-column: 3; }
.four  { background: #dce319aa; grid-column: 4; }
<div class="grid">
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
</div>
<hr><p>Three and Four should fill the space:</p>
<div class="grid">
  <div class="one">One</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
</div>
like image 30
DirectionUnkown Avatar answered Sep 15 '25 21:09

DirectionUnkown