Search code examples
javascripthtmlcsscentertext-align

how to text align center for the text with space and line break


I have the following example below:

.wrapper {
  text-align: center;
  border: 1px solid red;
  background-color: white;
  color: black;
  width: 240px;
  height: 200px;
  font-size: 36px;
  line-height: 43px;
}
<textarea class="wrapper" autosize>THE GREAT BANGKOK SALE</textarea>

https://jsfiddle.net/ngoctuan001/cgLvh62o/2/

As you can see, I want to text-align the text in the textarea tag. Because the text area got a fixed width, it will try to break to next line when there is a space. However, when that happen, that row is slightly not center in human eyes due to the space.

enter image description here

enter image description here

As you can see in the screen shot above, the red line in the right hand side is always slightly longer than the red line in the left hand side, this is because the computer treats the space (highlighted) as 1 more character. But in human eyes, this is not considered as center aligned

Is there anyway to fix this ? Thanks


Solution

  • Unfortunately there is no concrete CSS solution at the time of writing to achieve the desired result

    Alternative: use contenteditable

    .container {
      width: 100px;
      height: 150px;
      background: #eee;
      display:flex;
      align-items: center;
      justify-content: center;
    }
    
    .text {
      text-align: center;
      word-break: break-all;
      margin: 10px;
    }
    <div class="container">
      <div class="text" contenteditable=true>click here and edit</div>
    </div>