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

CSS3 Grid布局:实现首末列文本对齐边缘且列间文本间距均等

解决CSS Grid卡号布局的对齐问题

我明白你的需求了——用CSS Grid布局4列4位数字的卡号,要让第一列紧贴网格左边缘,最后一列紧贴右边缘,同时四列之间的间距完全均等。之前用1fr均分列宽再加文本居中的方式,确实会导致卡号和容器边缘之间有空白,达不到预期效果。

下面是调整后的解决方案:

核心思路

我们需要让Grid列的宽度适配内容(因为每列都是4位数字,宽度相近),同时通过justify-content: space-between来实现:首列左对齐容器边缘、末列右对齐边缘,且列间距自动均等分配。

修改后的代码

CSS部分:

.credit-card{
  position: relative;
  display: grid;
  /* 调整列布局为自适应内容 */
  grid-template-columns: repeat(4, auto);
  /* 关键:让列内容两端对齐,中间间距自动均等 */
  justify-content: space-between;
  grid-template-rows: auto auto auto 1fr;
  grid-row-gap: 5px;
  width: 326px;
  padding:27px 27px 17px 27px;
  border-radius: 6px;
  background: #fff;
  border: 1px solid #efefef;
  box-shadow: 0px 2px 24px 0px rgba(0,0,0, 0.07);
  box-sizing: border-box;
  overflow: hidden;
  
  .card-number-section{
    grid-row:3;
    padding-bottom: 20px;
    font-family: $family-open-sans;
    font-size: 18px;
    font-weight: 600;
    color: #4a4a4a;
    /* 可选优化:用等宽字体保证每列视觉宽度一致 */
    /* font-family: monospace; */
  }
}

HTML部分(无需修改,保持原Angular代码即可):

<ng-container *ngFor="let section of _CardNumberSections">
  <div class="card-number-section">
    {{ section }}
  </div>
</ng-container>

说明

  1. grid-template-columns: repeat(4, auto):让每列宽度自动适配内部的4位数字内容,避免1fr均分带来的多余空白。
  2. justify-content: space-between:这是实现需求的核心属性——它会让Grid容器内的列元素,第一个紧贴左边缘,最后一个紧贴右边缘,中间元素自动分配间距,保证所有列之间的空隙完全相等。
  3. 可选优化:如果使用的非等宽字体导致4位数字宽度略有差异,可以给.card-number-section添加font-family: monospace(等宽字体),让每列视觉宽度完全一致,布局更整齐。

这样调整后,就能完美实现你想要的对齐效果啦!

内容的提问来源于stack exchange,提问作者Jonas Mohr Pedersen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:09:35