如何使用 space 和换行符使文本居中对齐

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

我有下面的例子:

.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/

如您所见,我想对 textarea 标记中的文本进行文本对齐。因为文本区域有一个固定的宽度,当有 space 时它会尝试换行到下一行。然而,当发生这种情况时,由于 space.

,该行在人眼中稍微不居中

正如您在上面的屏幕截图中看到的,右侧的红线总是比左侧的红线稍长,这是因为计算机将 space (突出显示)作为 1 个字符。但是在人眼中,这不算居中对齐

有办法解决这个问题吗? 谢谢

一个解决方案是在 div.

上使用 contentEditable="true"

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content

<div class="wrapper" contentEditable="true">
  THE GREAT BANGKOK SALE
</div>

这将使内容正确居中,您也可以对其进行编辑。

要获取您的内容:

const content = document.querySelector('.wrapper').innerText;

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

备选方案:使用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>

把你的文字放在p标签里试试

.wrapper
{
display: flex;
    align-items: center;
    justify-content: center;

}