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

如何使用Grid布局将元素垂直移动到容器底部?

Grid布局实现顶部双div+底部单div的问题修正

原代码的核心问题

  • 默认Grid是单行多列布局,三个div处于同一网格行中,align-self: end仅能让第三个div在当前单元格内底部对齐,无法到达容器底部。
  • align-content: start会让整个网格内容块紧贴容器顶部,进一步限制了第三个div的位置调整。

修正方案(两种实现方式)

方式一:划分三行,精准控制每行位置

body {
  display: grid;
  height: 500px;
  /* 创建三行:前两行自适应内容高度,第三行占满剩余空间 */
  grid-template-rows: auto auto 1fr;
  justify-content: center; /* 水平居中所有网格项 */
  background: gray;
  margin: 0; /* 清除body默认外边距 */
}

div {
  width: 50px;
  height: 50px;
  background: red;
}

div:nth-of-type(3) {
  grid-row: 3; /* 指定第三个div放在第三行 */
  align-self: end; /* 在第三行单元格内底部对齐 */
  background: blue;
}

方式二:两行布局,更简洁高效

body {
  display: grid;
  height: 500px;
  /* 创建两行:第一行占满容器剩余空间,第二行自适应内容 */
  grid-template-rows: 1fr auto;
  justify-content: center;
  background: gray;
  margin: 0;
}

div {
  width: 50px;
  height: 50px;
  background: red;
}

/* 前两个div在第一行顶部对齐 */
div:nth-of-type(1), div:nth-of-type(2) {
  align-self: start;
}

/* 第三个div放在第二行,自然处于容器底部区域 */
div:nth-of-type(3) {
  grid-row: 2;
  background: blue;
}

HTML代码无需修改:

<div></div>
<div></div>
<div></div>

内容的提问来源于stack exchange,提问作者j-0-n-e-z

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:22:41