Home > Back-end >  How to horizontally center text of zero-width element?
How to horizontally center text of zero-width element?

Time:11-09

As you can see in the snippet below, the left border represents the center of the element. The text begins to the right of the border.

However, I need the text to be centered on the border, while remaining zero-width.

So I need to shift the text to the left somehow, but text-align: center and text-align: middle have no effect.

I can't translate the entire element because then the border would be translated to the wrong place.

The purpose of this element is to be a tick mark for the horizontal axis of a chart.

div {
  width: 0;
  border-left: 1px solid black;
}
<div>foo</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

flexbox is the easiest way here:

div {
  width: 0;
  border-left: 1px solid black;
  display:flex;
  justify-content:center;
}
<div>foo</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Thanks to Sato Takeru's comment I've decided to use a pseudo element.

div {
  width: 0;
  border-left: 1px solid black;
}

div::before {
  position: absolute;
  text-align: center;
  content: 'foo';
  width: 4em;
  transform: translateX(-2em);
}
<div>&nbsp;</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

span {
  position: relative;
  width: 0;
}

span:after{
  content: '';
  position: absolute;
  width: 1px;
  height: 100%;
  background: #000;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
<span>foo</span>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related