如何使基于子元素的整个元素居中?

How to center an whole element based around a child element?

Image showing the center line where the "vs" should be on

我会尽可能清楚地解释我的问题。这里我试图让 "vs" 在中心线,左右元素在它旁边流动。

我试过使用 flex-box 但它居中了整个东西,正如你在上面的照片中看到的那样,但不是我想要实现的。

谢谢!

这是我尝试过的片段:

<div class='flex 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>
.flex {
  display: flex;
}

.page-container {
  align-items: center;
  justify-content: center;
  margin: 1.5rem;
  max-height: 9rem;
  overflow: hidden;

  .team-name {
    align-items: center;
  }
  .team-logo {
    height: 6rem;
    max-width: 7rem;
    margin: 0 5rem;
    overflow: hidden;
  }
  .vs {
    align-self: center;
  }
}

尝试

.page-container {
  justify-content: space-between;
}

.page-container {
  justify-content: space-evenly;
}

如果您不希望团队名称与边缘对齐

flex-basis:0 确保元素真正共享可用的 space,而不是先计算每个 flex item 的内容,然后将剩余的分配给 space。

剩下的只是简单的对齐。

flex: 1 0 0;

的缩写
flex-grow:1;   // make element grow
flex-shrink:0; // prevent element from shrinking (preference really)
flex-basis:0;  // ignore content width

/* Just for illustrating, To be removed */

body * {
  border: 1px solid;
  padding: 10px;
}

[center] {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 1.5rem;
}


/* ============ */

.flex {
  display: flex;
}

.page-container {
  margin: 1.5rem;
  max-height: 9rem;
  overflow: hidden;
  align-items: center;
}

.team-name {
  flex: 1 0 0;
  align-items: center;
  justify-content: flex-end;
}

.team-logo {
  max-height: 6rem;
  max-width: 7rem;
  overflow: hidden;
  margin: 0 10px;
}

.vs {
  margin: 0 10px;
}

.team-name~.team-name {
  justify-content: flex-start;
}
True center example
<div center="">
  <div>VS</div>
</div>

<div class="flex page-container">
  <div class="flex team-name">
    THIS TEAM NAME IS LONG
    <img class="team-logo" src="https://i.picsum.photos/id/163/200/300.jpg">
  </div>
  <div class="vs">VS</div>
  <div class="flex team-name">
    <img class="team-logo" src="https://i.picsum.photos/id/163/200/300.jpg"> SHORT NAME
  </div>
</div>