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

如何使左对齐的2个Grid项居中,同时兼容4列布局?

解决团队成员列表居中布局问题

问题说明

需要让2个团队成员元素在一行中居中显示(而非靠右),同时保证当一行有4个成员时布局保持一致,因此采用了4列的Grid布局。

解决方案

通过调整Grid布局的列跨度规则,实现2个成员时居中、4个成员时满排的效果:

修改后的CSS代码

.members.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: 1fr;
  grid-column-gap: 69px;
  grid-row-gap: 40px;
  justify-items: center;
  margin: auto;
}

.members .teamMember {
  text-align: center;
}

/* 当仅有2个成员时,每个成员占据2列宽度,实现居中 */
.members.grid .teamMember:nth-last-child(2):first-child,
.members.grid .teamMember:nth-last-child(1):nth-child(2) {
  grid-column: span 2;
}

.teamMember a img,
.teamMember a .nophotoContainer {
  border: 7px solid white;
  transition: border 1s;
}

.nophotoContainer {
  border-radius: 50%;
  position: relative;
  height: 300px;
  width: 300px;
  background-color: #032c41;
}

.nophotoContent {
  position: absolute;
  top: 50%;
  left: 50%;
  text-align: center;
  transform: translate(-50%, -50%);
}

效果说明

  • 当团队成员为2个时,每个成员会自动占据2列宽度,刚好填满4列的Grid容器,整体居中显示。
  • 当团队成员为4个时,每个成员默认占据1列,保持满排的布局效果。

保留的HTML结构

<div class="members grid">
  <div class="teamMember">
    <a href="#">
      <div class="nophotoContainer has-background">
        <div class="nophotoContent">
          <h4>Kent H</h4>
          <h6>Member Role</h6>
        </div>
      </div>
    </a>
  </div>
  <div class="teamMember">
    <a href="#">
      <div class="nophotoContainer has-background">
        <div class="nophotoContent">
          <h4>Bruce H</h4>
          <h6>Member Role</h6>
        </div>
      </div>
    </a>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:55:20