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

Time:09-23

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 >
  <div >1</div>
  <div >1/A</div>
  <div >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 |
---------

CodePudding user response:

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 >
  <div >1</div>
  <div >1/A</div>
  <div >1/B</div>
</div>

CodePudding user response:

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 >
  <div >1</div>
  <div >1/A</div>
  <div >1/B</div>
  <div >2/C</div>
  <div >3/C C</div>
</div>

  •  Tags:  
  • css
  • Related