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

使用CSS Grid实现除最后一个子元素外其余居顶的布局方案

使用CSS Grid实现顶部元素居顶、最后一个元素居底的布局方案

可以通过显式定义网格行轨道的方式实现需求,无需额外添加包裹容器,具体实现如下:

核心思路

  1. 给网格容器设置grid-template-rows,让前三个行轨道高度为auto(匹配子元素的固定高度),最后一个行轨道占据容器剩余所有空间(用1fr);
  2. 给最后一个子元素设置align-self: end,让它在自己的行轨道内垂直对齐到底部。

这样前三个子元素会自然停留在容器顶部,最后一个元素则固定在容器底部,完全符合需求。

修改后的代码示例

.container {
  display: grid;
  height: 100vh;
  background-color: grey;
  /* 定义4行:前3行自适应内容高度,最后一行占剩余空间 */
  grid-template-rows: repeat(3, auto) 1fr;
}

.top_one {
  height: 50px;
  background-color: red;
}

.top_two {
  height: 50px;
  background-color: green;
}

.top_three {
  height: 50px;
  background-color: purple;
}

.bottom_copyright {
  align-self: end;
  height: 50px;
  background-color: blue;
}
<div class="container">
  <div class="top_one">box 1</div>
  <div class="top_two">box 2</div>
  <div class="top_three">box 3</div>
  <div class="bottom_copyright">copyright</div>
</div>

原理说明

  • grid-template-rows: repeat(3, auto) 1fr:将容器垂直划分为4个行轨道,前3个轨道高度由子元素的固定高度决定,最后一个轨道用1fr占据容器剩余的所有垂直空间;
  • align-self: end:让最后一个子元素在自己的行轨道内(即剩余空间的轨道)垂直对齐到底部,而前三个子元素所在的轨道高度与自身高度一致,自然处于容器顶部。

如果后续顶部子元素数量变化,只需调整repeat()内的数字即可,灵活性很高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:23:02