如何在具有网格布局的 empty/full 页面上强制页脚位于页面底部

How can I force footer on bottom of page on empty/full page with grid layout

我有几页内容不多。整个网站采用网格布局 - 基本页眉、主体和页脚:

目标是将页脚设置到屏幕底部,如果页面上没有像这样的大量内容,则使用内容中的空格:

出于演示目的,我在此页面上使用了 50vh 的底部边距。

但是,如果博客 post 大于 100vh,则页脚仍应出现在底部 - 当然没有空格:

用户需要滚动才能看到页面底部的页脚。

实现此行为的“最佳实践”方式是什么(最好不用 JS(?))?


一些代码供那些可能想查看网页结构的人使用:

/* inside this class the content is wrapped into the grid layout */
.container {
  display: grid;

  grid-template-areas:
  "header header header header header"
  ". recent-posts recent-posts recent-posts ."
  "footer footer footer footer footer";

  grid-template-columns: repeat(5, minmax(0, 1fr));

  gap: 10px;
}
/* setting header, main and footer as grid layout */
header {
  grid-area: header;

  border-bottom: 1px solid;
  border-radius: 4px;
  margin-bottom: 2vh;

}

main {
  grid-area: recent-posts;
}

footer {
  grid-area: footer;

  margin-top: 1vh;
  padding: 0.2vh;
  border: 1px solid;
  border-radius: 4px;
}

如果有人想查看整个代码,我会在 GitLab.

上发布源代码

如果我们在这种情况下使用 flexbox,这将是这样。

section 将充当除页眉和页脚之外的所有数据的容器。由于该部分定义为 flex:1,因此它将占用整个 space,但页眉和页脚除外。

这样,如果部分内容溢出,页脚也会进一步向下推。您不必担心任何此类情况。

main {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

header, section, footer {
  border: 1px solid #ddd;
  padding: 10px;
}

section {
  flex: 1;
}
<main>
    <header>
        Something
    </header>
    <section class="container">Another thing</section>
    <footer>
        Footer
    </footer>
</main> 

我想出了一个解决方案,将来可能会对其他人有所帮助:

里面 .container class 我补充说:

.container {
[…]
/* this forces the footer to stay at the bottom even if the content doesn't fill up the page */
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}

其中 grid-template-rows 等于网格布局的行数。


我编辑了 CSS 文件以删除整个网格布局周围的填充,这使得页面比 100vh 稍微大一点,并以这种方式添加了一个滚动条。

相反,我在页眉和页脚本身添加了边距:

footer on low-content pages footer with more content

在移动设备上,由于 URL 栏,您可能需要滚动才能看到内容:

landing on mobile startpage scroll on mobile to see 100vh


我将此问题标记为已解决,因为此解决方案完全符合我的要求;不过,如果有人知道更好的方法,请写下答案!