【问题标题】:How to make an element fill the remaining viewport height?如何使元素填充剩余的视口高度?
【发布时间】:2018-04-26 13:07:22
【问题描述】:

我想使用 CSS 网格。我认为是这样的……

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: grid;
  grid-template-rows: auto auto [whatever's left of the vh] auto auto;
  position: relative;
}

【问题讨论】:

  • 如果这是唯一的情况,那么最好使用 Flexbox。

标签: css grid-layout css-grid


【解决方案1】:

display: flexheight: 100vh设置视口并添加到最后一个元素 flex-grow: 1

这是一个小小提琴:

https://jsfiddle.net/omA123/y4j9nhpy/

【讨论】:

  • 完美解决方案!
【解决方案2】:

使用 CSS Grid,您需要包裹顶部两个元素和剩余空间,然后对其应用 display: grid

换句话说,您的图表实际上就是解决方案。

包装器的高度应为100vh...

html {
  height: 100%;
}

body {
  margin: 0;
  min-height: 100%;
  background: pink;
  display: grid;
  grid-template-rows: 100vh auto auto;
  position: relative;
}

.wrapper {
  display: grid;
  grid-template-rows: auto auto 1fr;
}

header {
  background: green;
  padding: .25em;
}

nav {
  background: orangered;
  padding: .25em;
}

main {
  background: rebeccapurple;
}

footer {
  background: yellow;
}

.subfooter {
  background: blue;
}
<div class="wrapper">
  <header>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Ratione magnam placeat quia iusto, quisquam cum temporibus modi, ex dolorem velit fuga! Minima, ex.
  </header>

  <nav>
    Lorem ipsum dolor, sit amet consectetur adipisicing elit.
  </nav>
  <main></main>
</div>
<footer>Lorem, ipsum.</footer>
<div class="subfooter">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ex dignissimos ratione maxime officia eum. ea!
</div>

【讨论】:

  • 就是这样。我没想到包装前三个元素!谢谢。
【解决方案3】:

你可以使用 flex 来做到这一点。

.a {
  width: 100%;
  height: auto;
}

.remaining {
  width: 100%;
  flex-grow: 1;
}

.holder {
  display: flex;
  flex-direction: column;
  height: 100%;
}

html,
body {
  height: 100%;
}

HTML 代码:

<div class="holder">
  <div class="a">
   Content here
  </div>
  <div class="a">
    Content here
  </div>
  <div class="remaining">
    Content here
  </div>
</div>

【讨论】: