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

如何创建始终居中1列的三列flexbox容器?

Fix: Keep Blue Center Box Horizontally Centered Regardless of Side Content

Got it, let's lock that blue center box in the exact horizontal center no matter what text is in the red side columns. The problem right now is your flex-grow: 1 setting on the side boxes—they expand based on their content length, so if one side has longer text, it pushes the center box off its true center position.

Here are two reliable solutions to fix this:

Solution 1: Use CSS Grid (Simpler & More Intuitive)

Grid makes this scenario trivial because we can explicitly set the left and right columns to take equal space, while the center column only uses the space it needs. This guarantees the center box stays perfectly centered.

Update your CSS like this:

.table { width: 100%; }
.item { 
  width: 100%; 
  display: grid; /* Swap flex for grid */
  grid-template-columns: 1fr auto 1fr; /* Equal left/right space, auto-sized center */
  align-items: center; 
  margin-bottom: 5px;
}
.center-box { flex-basis: 70px; background: blue; text-align: center; color: white; }
.side-box { background: red; text-align: center; color: white; }
/* Optional: Add text truncation to prevent long side content from breaking the layout */
.side-box {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Solution 2: Adjust Flex Layout Properties

If you want to stick with flexbox, we can force the left and right boxes to take up exactly 50% of the available space each—even when their content lengths differ. This ensures the center box stays dead-center.

Modify your CSS like so:

.table { width: 100%; }
.item { width: 100%; display: flex; align-items: center; margin-bottom: 5px }
.center-box { flex-basis: 70px; background: blue; text-align: center; color: white; }
.side-box { 
  flex: 1 1 50%; /* Force equal width for left and right boxes */
  background: red; 
  text-align: center; 
  color: white;
}
/* Optional: Prevent long text from breaking layout */
.side-box {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Either approach will keep your blue center-box perfectly centered, no matter how long or short the text in the side columns is.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:02:33