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

如何用CSS Grid让Grid项Two与Three内容处于同一水平高度?

CSS Grid 布局对齐解决方案

你需要让所有网格项在容器内垂直居中,同时让项Two的内容和项Three的内容处于同一水平线,以下是实现方法:

修改后的完整代码

CSS

h1, p {
  font-family: Lato;
}

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 100px;
}

.wrapper div {
  background-color: yellow;
  border: 1px solid red;
  align-self: center; /* 默认让所有项垂直居中 */
}

.box1 {
  grid-column: 1 / 4;
  grid-row: 1 / 3;
}

.box2 {
  grid-column: 1;
  grid-row: 3 / 5;
  align-self: start; /* 取消box2的垂直居中,让内容靠顶部 */
  transform: translateY(50%); /* 向下偏移自身高度的50%,对齐第三行中心 */
}

HTML

<div class="wrapper">
  <div class="box1">One</div>
  <div class="box2">Two</div>
  <div class="box3">Three</div>
  <div class="box4">Four</div>
  <div class="box5">Five</div>
</div>

实现逻辑

  • 全局设置align-self: center,确保box1、box3、box4、box5的内容在各自网格区域内垂直居中。
  • 对box2单独调整:align-self: start让它的内容从网格区域顶部开始,再通过transform: translateY(50%)将内容向下移动自身高度的一半,刚好和box3所在行的垂直中心对齐,满足“Two和Three内容完全在同一水平线”的需求。
  • 这种方式不会改变网格的布局结构,只是调整box2内容的位置,兼容性也较好。

内容的提问来源于stack exchange,提问作者sir-haver

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:40:36