Copper
Copper

Reputation: 35

How do I center text with CSS so that one of the elements is always at the center of parent element?

I have an element in which I want to show two team names like so: Team1 vs. Team2. However, when the name of one team is considerably longer than the other one, the vs. gets off-centered.

How can I achieve the "vs." part always staying dead-center and having the two elements go right next to it on either sides? All elements are text.

Example:

--------Team1-vs.-Team2--------
Team1Longname-vs.-Team2--------
--------Team1-vs.-Team2Longname

Upvotes: 1

Views: 58

Answers (1)

Hao Wu
Hao Wu

Reputation: 20859

You can use flexbox and assign both of the team names flex: 1. Then give the team name on the left text-align: right

.wrapper {
  display: flex;
}

.wrapper .team {
  flex: 1;
}

.wrapper .vs {
  margin: 0 10px;
}

.wrapper .team:first-child {
  text-align: right;
}
<div class="wrapper">
  <span class="team">Team 1</span>
  <span class="vs">vs.</span>
  <span class="team">Team 2</span>
</div>

<div class="wrapper">
  <span class="team">Team 1</span>
  <span class="vs">vs.</span>
  <span class="team">Team 2 with A Long Name</span>
</div>

<div class="wrapper">
  <span class="team">Team 1 with A Long Name</span>
  <span class="vs">vs.</span>
  <span class="team">Team 2</span>
</div>

Upvotes: 3

Related Questions