Search code examples
cssbordertext-align

How to horizontally center text of zero-width element?


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>


Solution

  • flexbox is the easiest way here:

    div {
      width: 0;
      border-left: 1px solid black;
      display:flex;
      justify-content:center;
    }
    <div>foo</div>