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

如何使用CSS实现文本布局时指定元素始终位于父容器正中心

实现方案

推荐使用CSS Grid布局实现,无需复杂定位,自适应能力强,完全满足vs.固定在容器中心、两队名紧贴两侧的需求。

HTML结构

<!-- 父容器 -->
<div class="match-team-wrapper">
  <span class="team team-left">Team1Longname</span>
  <span class="vs-text">vs.</span>
  <span class="team team-right">Team2</span>
</div>

CSS代码

.match-team-wrapper {
  display: grid;
  /* 三列布局:左右列平分剩余空间,中间列宽度随内容自适应 */
  grid-template-columns: 1fr auto 1fr;
  width: 400px; /* 可自定义父容器宽度,也可设为100%撑满上级容器 */
  /* 控制队名和vs.的间距,可按需调整 */
  column-gap: 8px;
}

.team-left {
  /* 左队名靠右对齐,紧贴vs.左侧 */
  text-align: right;
  /* 可选配置:队名过长时显示省略号,不会挤偏vs.位置 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.team-right {
  /* 右队名靠左对齐,紧贴vs.右侧 */
  text-align: left;
  /* 同上可选配置 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.vs-text {
  white-space: nowrap;
}

备选Flex兼容方案

如果需要兼容不支持Grid的老旧环境,可以用Flex+绝对定位实现:

.match-team-wrapper {
  position: relative;
  display: flex;
  width: 400px;
}

.vs-text {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  white-space: nowrap;
}

.team {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.team-left {
  text-align: right;
  /* 预留vs.的宽度,避免队名过长覆盖vs.,数值根据vs.的实际宽度调整 */
  padding-right: 25px;
}

.team-right {
  text-align: left;
  /* 同上预留宽度 */
  padding-left: 25px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 21:54:05