【问题标题】:How to account for dynamic rows in a CSS Grid setup?如何在 CSS Grid 设置中考虑动态行?
【发布时间】:2026-02-14 04:30:01
【问题描述】:

我的主页仪表板具有div 元素堆叠在一起的一般结构(每个元素都是屏幕宽度并提供不同类型的信息)。

我通过 CSS Grid 管理块的高度:整个应用程序是 min-height: 100vh;,行是 auto,除了一个是 1fr。效果很好。

我现在面临其中一条线动态存在或不存在的情况。这是因为它实际上是一个 Vue 组件,以v-if 有条件地显示。问题是 CSS 部分不知道它的存在,grid-template-rows 已修复。这会导致在切换时错误的行是 auto1fr

如何解决?

我能想到的一种方法是以 CSS 将其计为一行的方式强制组件的存在。现在,当它关闭时,我在开发工具中看到此元素为 <!----> == $0

另一种方法是“描述”列模板,而不是固定列表。类似于“尽可能使用auto,然后使用1fr 和一个auto


下面的两个代码片段模拟了我的问题。

第一种是所有元素都可见的情况

#app {
  display: grid;
  min-height: 100vh;
  grid-template-rows: auto auto 1fr;
}

#footer {
  align-self: end;
}

div {
  border-style: dashed;
  border-width: 1px;
}
<div id="app">
  <div>this line is always visible</div>
  <div>this one is toggled - here it is visible</div>
  <div id="footer">this is the footer</div>
</div>

下面的代码是相同的,但第二行被切换(在这里注释掉,在实际代码中通过v-if 禁用)。看看它如何影响不再位于底部的页脚,因为 CSS 没有改变(= 没有适应消失的行)

#app {
  display: grid;
  min-height: 100vh;
  grid-template-rows: auto auto 1fr;
}

#footer {
  align-self: end;
}

div {
  border-style: dashed;
  border-width: 1px;
}
<div id="app">
  <div>this line is always visible</div>
  <!-- <div>this one is toggled - here it is not visible anymore </div> -->
  <div id="footer">this is the footer</div>
</div>

【问题讨论】:

  • 你能分享你的代码吗?所以我们可以看到结构、元素数量、模板等
  • @TemaniAfif:好的,有一个想法来最小化代码,这些例子现在反映了我的问题。
  • 嗯...为什么不使用 flexbox 呢?

标签: html css vue.js vue-component css-grid


【解决方案1】:

一个想法是明确定义页脚的行以始终使用最后一个:

#app {
  display: grid;
  min-height: 100vh;
  grid-template-rows: auto auto 1fr;
}

#footer {
  align-self: end;
  grid-row:-1;
}

div {
  border-style: dashed;
  border-width: 1px;
}
<div id="app">
  <div>this line is always visible</div>
  <div>this one is toggled - here it is visible</div>
  <div id="footer">this is the footer</div>
</div>

<div id="app">
  <div>this line is always visible</div>
  <!--<div>this one is toggled - here it is visible</div>-->
  <div id="footer">this is the footer</div>
</div>

【讨论】:

  • 啊,这是个好主意。我一直在寻找这种相对计数,但不知道它存在。当grid-template-rows 中的元素数量与实际行数不匹配时,grid-template-rows 中的auto 是如何解释的? (当切换行关闭时)
  • @WoJ 中间的 auto 将被计算为 0,但您将始终有 3 行,第二行为空,因为其中没有放置任何项目
【解决方案2】:

CSS grid 系统不是动态行/列的最佳选择。当您提前知道布局将是什么时,这是最好的。

但是,您可以做一些事情。

选项 1

您可以使用内联样式定义grid-template-rows: auto auto 1fr;(在父元素内,并使用javascript 进行控制。

所以,在这种情况下:

<div id="app" style="grid-template-rows: auto auto 1fr;">

随着行数的变化,样式的值也随之改变。

<div id="app" style="grid-template-rows: auto 1fr;">

选项 2

提前定义几个类,根据行数切换到合适的类:

.rows-2
  grid-template-rows: auto 1fr;
}

.rows-3
  grid-template-rows: auto auto 1fr;
}
<div id="app" class="rows-2/3">

这两种解决方案都需要一些 javascript 来调整到所需的网格布局。

【讨论】: