-1

I have a span positioned as absolute inside a div (with top and left values set). The span is connected to user input and when the user inputs text the span exands with the given text towards the right to contain the text, but I'd like it to grow in both sides, which means when user inputs a word of 7 characters, the character in order #4 should be in the exact center.

Is there anyway to achieve this in pure CSS? or a way to mutate the value of left using JS but with decent accuracy.

1 Answers1

1

You could use flexbox, or text-align to do this but if you're tied to absolute positioning then there's ways to do that too:

<div>
  <span>Centered Text</span>
</div>

<style>

div {
  position: relative;
  width: 200px;
  height: 40px;
  border: 1px solid black;
}

span {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

</style>

This will put the top left corner of the <span> at the center of the <div> then move the <span> half left and half up putting it in the center of the <div>

Ryan Allred
  • 278
  • 2
  • 12