html - 部分填充时如何强制 body 成为屏幕的大小?

标签 html css css-grid

我想建立一个网站,其中有一个固定的标题、一个可变的内容和一个在页面未完全填充时位于底部的页脚。我将使用 CSS Grid Layout为此。

当高度已知时扩展内容元素很容易:

div {
  border-width: 1px;
  border-style: solid;
}

#container {
  width: 200px;
  height: 200px;
  display: grid;
  grid-template-rows: auto 1fr auto;
}
<div id="container">
  <div>hello </div>
  <div>world</div>
  <div>three</div>
</div>

然后我尝试在全窗口浏览器上重现它,我不知道如何告诉应用程序“如果没有足够的内容,高度就是浏览器的大小,否则就是内容”。我认为 min-height: 100%; 应用于 body 会很好 - 但事实并非如此:

body {
    display: grid;
    grid-template-rows: auto 1fr auto;
    grid-template-columns: 1fr auto;
    min-height: 100%;
}
.navbar {
    grid-row-start: 1;
    grid-row-end: 2;
    grid-column-start: 1;
    grid-column-end: 3;
}
.main {
    grid-row-start: 2;
    grid-row-end: 3;
    grid-column-start: 1;
    grid-column-end: 2;
}
.toc {
    grid-row-start: 2;
    grid-row-end: 3;
    grid-column-start: 2;
    grid-column-end: 3;
}
.footer {
    grid-row-start: 3;
    grid-row-end: 4;
    grid-column-start: 1;
    grid-column-end: 3;
}

此代码创建了正确的网格,但 body 的大小不是浏览器的整个高度:

enter image description here

最佳答案

使用 min-height: 100vh 代替 min-height:100%

百分比高度很棘手,因为它们通常需要在父元素 ( full explanation) 上定义高度。

来自规范:

5.1.2. Viewport-percentage lengths: the vw, vh, vmin, vmax units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

  • vw unit - Equal to 1% of the width of the initial containing block.
  • vh unit - Equal to 1% of the height of the initial containing block.
  • vmin unit - Equal to the smaller of vw or vh.
  • vmax unit - Equal to the larger of vw or vh.

关于html - 部分填充时如何强制 body 成为屏幕的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45436103/

相关文章:

javascript - JQuery - 显示多个div

html - 在 div 上上课,使幻灯片放映高度更高

在 Mac 上的 Outlook 中损坏的 HTML 电子邮件签名 - 在 Windows 上工作正常吗?

css - 如何仅将溢出 y 添加到特定的 div

html - 使行高适应 CSS 网格中的动态内容

html - CSS 网格部分响应

html - 设置主体宽度会改变 div 的绝对定位

html - 只有一行比应有的大的表格

HTML 下拉菜单不起作用

CSS Grid 自动调整列自动换行