【问题标题】:Force div to occupy the rest of space with css-grid使用 css-grid 强制 div 占据剩余空间
【发布时间】:2020-06-14 19:13:00
【问题描述】:

有没有办法用css-grid 强制网格容器延伸到屏幕的末尾(参见下面的sn-p,为了可视化,我使用height: 80vh; 作为手动方法)

编辑:我总是可以知道页眉和页脚的高度,然后使用例如grid-template-rows: calc(100vh - ...px);

body {
  margin: 0;
}

.header {
  height: 100px;
  background: #f6eeee;
  margin: 5px 0px;
  border: 1px solid #cacaca;
  padding: 5px;
}

.grid {
  display: grid;
  grid-template-columns: 200px 1fr 200px;
  grid-column-gap: 10px;
  border: 2px solid #000;
  overflow: hidden;
  margin: 5px 0px;
  border: 1px solid #cacaca;
}

.left {
  display: grid;
  grid-template-rows: calc(100vh - 2*112px - 2*12px);
  /* 100px height + 10px padding + 2px border */
  /* 10px margin + 2px border */
  overflow: auto;
  /* height: 80vh; */
}

.left>div {
  height: 40000px;
  background: #e7e6de;
  padding: 5px;
}

.right {
  height: 300px;
  background: #e3e7e9;
  padding: 5px;
}
<body>
  <div class="header">whatever relevant</div>
  <div class="grid">
    <div class="left">
      <div>lots of content</div>
    </div>
    <div class="right">another content</div>
  </div>
  <div class="header">whatever relevant 2</div>
</body>

【问题讨论】:

  • 它已经可以了,即使没有 80vh
  • 我这样做是因为我在问题的编辑部分添加了我所说的内容,但是我必须手动调整数字,所以问题是这里是否有更直接的解决方案
  • 为什么不在 body 上使用 flexbox / column 并将 max-height 设置为 100vh。然后你可以强制网格为 flex:1。没有理由不能混合和匹配布局方法。

标签: css flexbox css-grid


【解决方案1】:

最简单/最简洁的解决方案是 flexbox。您可以将其用于静态页眉/页脚高度或动态,只需分别更改在 px/vh 中设置的页眉/页脚高度。

无需使用计算函数,它可能也是创建动态网格的最佳方式。

.site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
  padding: 0;
  margin: 0;
}

.site-content {
  flex: 1;
}
header, footer {
  height: 20vh;
  background-color: orange;
  color: white;
}
<body class="site">
  <header>Navigation</header>
  <main class="site-content">content goes here</main>
  <footer>Footer stuff</footer>
</body>

【讨论】: