Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position an HTML element by center

Tags:

html

css

What's the proper way to position an HTML element according to a center handle?

In this example:

  XXXXXXXXX
      |
      |
     123px

Assume the element should be position at absolute position left: 123px; but the text should be centered at that point, not start at it. The element text is dynamic, so I have no way of setting a static negative margin-left on it.

Is there a pure CSS way to achieve this? The JS way of measuring offsetWidth and then setting left after calculating width / 2 won't neccesarily work in my case due to various limitations.

like image 218
Yuval Adam Avatar asked Mar 13 '23 05:03

Yuval Adam


1 Answers

One posibility is to set a transform translateX -50%

p {
  position: relative;
  display: inline-block;
      left: 100px;
    transform: translateX(-50%);
}
<p>ONE</p>
<br>
<p>TWO, LONGER</p>
<br>
<p>THREE, the longest</p>
like image 181
vals Avatar answered Mar 16 '23 06:03

vals