How to align a text horizontally centered by it's first character with CSS?

Viewed 25

For example, I have a <div> element like this:

.box {
  display: flex;
  flex-direction: column;
  width: 100px;
  height: 100px;
  background-color: yellow;
  align-items: center;
 }
<div class="box">
  <div class="item">1</div>
  <div class="item">1/A</div>
  <div class="item">1/B</div>
</div>

My goal is to align items horizontally centered by the first characters, so in the example, the '1' characters need to be centered, not the whole text.

Wanted result:

---------
|   1   |
|   1/A |
|   1/B |
---------
2 Answers

Add the following to your CSS:

.item {
  transform: translateX(50%);
}

See the snippet below.

.box {
  width: 100px;
  height: 100px;
  background-color: yellow;
}

.item {
  transform: translateX(50%);
}
<div class="box">
  <div class="item">1</div>
  <div class="item">1/A</div>
  <div class="item">1/B</div>
</div>

I will make the width of all the elements equal to 1ch and also use font-variant-numeric: tabular-nums; to make sure all the number takes the same width

.box {
  display: flex;
  flex-direction: column;
  width: 100px;
  height: 100px;
  background:
    linear-gradient(lightblue 0 0) 50%/1px 100% no-repeat /* the center */
    yellow;
  align-items: center;
}

.item {
  font-variant-numeric: tabular-nums;
  width: 1ch;
  white-space: nowrap;
}
<div class="box">
  <div class="item">1</div>
  <div class="item">1/A</div>
  <div class="item">1/B</div>
  <div class="item">2/C</div>
  <div class="item">3/C C</div>
</div>

Related