如何以子元素VS为基准实现元素居中排布?
Got it, let's sort this out so your "VS" stays locked to the absolute middle of the page, no matter how long or short your team names are. The issue with your current flex setup is that justify-content: center centers the entire group of elements together, but doesn't anchor the "VS" to the page's horizontal midline. Here are two straightforward solutions:
Solution 1: CSS Grid (Cleanest & Most Reliable)
Grid makes this super intuitive because we can explicitly split the page space to force the "VS" into the exact center.
Updated HTML
<div class='page-container'> <div class='flex team-name'> THIS TEAM NAME IS LONG <img class='team-logo' src={TEAM_1_LOGO} /> </div> <div class='vs'>VS</div> <div class='flex team-name'> <img class='team-logo' src={TEAM_2_LOGO} /> SHORT NAME </div> </div>
Updated CSS
.flex { display: flex; align-items: center; /* Keep team name and logo vertically aligned */ } .page-container { display: grid; grid-template-columns: 1fr auto 1fr; /* Left: fill available space, VS: auto width, Right: fill available space */ align-items: center; margin: 1.5rem; max-height: 9rem; overflow: hidden; } .team-name { &:first-child { justify-content: flex-end; /* Push left team's content right, close to VS */ margin-right: 1rem; /* Add spacing between left team and VS */ } &:last-child { justify-content: flex-start; /* Push right team's content left, close to VS */ margin-left: 1rem; /* Add spacing between right team and VS */ } } .team-logo { height: 6rem; max-width: 7rem; margin: 0 1rem; /* Trimmed excessive margin for tighter alignment */ overflow: hidden; } .vs { /* Optional: Style to make it stand out */ font-size: 1.5rem; font-weight: bold; }
Solution 2: Adjusted Flexbox Layout
If you'd rather stick with flex, we can tweak the container rules to push the "VS" to the center.
CSS for Flex Approach
.flex { display: flex; align-items: center; } .page-container { display: flex; align-items: center; margin: 1.5rem; max-height: 9rem; overflow: hidden; } .team-name { flex: 1; /* Force both team containers to take equal available space */ &:first-child { justify-content: flex-end; margin-right: 1rem; } &:last-child { justify-content: flex-start; margin-left: 1rem; } } .team-logo { height: 6rem; max-width: 7rem; margin: 0 1rem; overflow: hidden; } .vs { align-self: center; font-size: 1.5rem; font-weight: bold; }
Quick Breakdown
- Grid Solution:
grid-template-columns: 1fr auto 1frguarantees the left and right columns split the page's available space equally, so the "VS" sits perfectly on the midline no matter the team name lengths. - Flex Solution:
flex: 1on both team containers makes them expand to fill identical space, thenjustify-contentpushes their content toward the center "VS".
Either approach will lock your "VS" to the exact middle of the page—no more shifting based on team name length!
内容的提问来源于stack exchange,提问作者Mir Ashif

