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

如何用CSS Grid实现两个同高并排且文本居中的链接

实现等高链接并居中对齐的CSS Grid方案

你的需求完全可以实现,问题出在原代码中给链接设置了align-self: center——这个属性会让链接元素在网格单元格内垂直居中,但不会让链接的高度撑满单元格,导致两个链接高度不一致。

只需要做两处修改即可解决:

  1. 移除链接的align-self: center,让Grid子元素默认拉伸填充整个网格单元格的高度
  2. 给链接添加Flex布局,实现文本在链接内部的垂直+水平居中

修改后的完整代码如下:

CSS

.box {
  display: grid;
  grid-template-columns: 50% 50%;
  grid-auto-rows: 1fr;
  height: auto;
  width: 300px;
  background: red;
}

a.button {
  background: green;
  color: white;
  padding: 10px;
  /* 用Flex实现文本居中 */
  display: flex;
  justify-content: center;
  align-items: center;
}

a:nth-child(2) {
  background: blue;
}

HTML

<div class="box">
  <a class="button">Batman</a>
  <a class="button">Spiderman eats Cornbread with Maple Syrup</a>
</div>

关键逻辑说明:

  • Grid容器的grid-template-columns: 50% 50%将容器分为等宽的两列,grid-auto-rows: 1fr确保行高由内容最高的单元格决定,所有单元格高度统一
  • 移除align-self: center后,链接作为Grid子元素会默认拉伸,填满整个网格单元格的高度,因此两个链接自然等高
  • 给链接设置display: flex并配合justify-content: center和align-items: center,可以让内部文本不管长度多少,都能在链接内实现完美的垂直+水平居中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:15:37