如何创建始终居中1列的三列flexbox容器?
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

