如果元素不存在/是可选元素,请不要在CSS网格中保留空间

问题描述

我正在使用grid-template为一行四列建立一个简单的网格结构。最左边的两列具有固定的宽度,其余两列应填充剩余的空间。

但是,第二列是可选-可能根本不存在。在这种情况下,我不想为其保留任何空间。最右边的两列应填充该空间。

这显然对于grid-template是不可能的。可能吗?

.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>

解决方法

尝试将display: flexflex属性一起使用,例如:

.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>