You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Grid布局下header/main/footer结构中两个section各占满一屏的实现问题

最终修改后代码

CSS 部分

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}

.container {
  width: 100%;
}

header,
footer {
  height: 100px;
  background-color: rgba(0,0,0,0.7);
}

header {
  /* 固定header相关配置 */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 999;
}

footer {
  width: 100%;
}

main {
  /* 避开固定header的高度,防止内容被遮挡 */
  padding-top: 100px;
}

section {
  display: block;
  background: #CFF;
  width: 100%;
  /* 单屏高度=可视窗口高度 - 固定header高度,刚好占满一整页 */
  height: calc(100vh - 100px);
}

.one {
  background: red;
}

.two {
  background: cyan;
}

HTML 部分和你原有代码一致,无需修改。


核心修改说明

  • 解决footer显示位置错误:删除了你原代码里container的grid布局,原来的grid限制了container最大高度为100%视口高度,导致两个section无法撑开父容器高度。现在每个section直接用calc(100vh - 100px)设置高度,两个section总高度为2倍视口高度,footer自然会跟在第二个section的最底部。
  • 解决header固定后隐藏的问题:给header加固定定位的同时补充了top:0;left:0;width:100%确保它固定在顶部且宽度铺满,加z-index:999避免被下层元素盖住,同时给main加了等于header高度的上内边距,避开header的覆盖区域。

如果需要实现滚动到对应位置自动吸附对齐的效果,还可以给main补充以下属性:

main {
  scroll-snap-type: y mandatory;
  overflow-y: scroll;
  height: calc(100vh - 100px);
}
section {
  scroll-snap-align: start;
}

内容的提问来源于stack exchange,提问作者DisplayYet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:06:03