【问题标题】:text-align justify by setting letter-space [duplicate]通过设置字母空间来对齐文本对齐[重复]
【发布时间】:2020-11-29 01:57:44
【问题描述】:

在下面的示例中,是否可以设置字母间距,以便所有三行都自动在两侧对齐?

我相信使用 javascript 可以做到这一点,但我更喜欢仅使用 css 的解决方案

.logo{
position:absolute;
text-align:justify;
text-align-last:justify;
}
<div class='logo'>LOREM IPSUM<br>DOLOR<br>SIT AMET</div>

【问题讨论】:

标签: html css


【解决方案1】:

这里有一个js解决方案:

function SplitText(node) {
  var text = node.nodeValue.replace(/^\s*|\s(?=\s)|\s*$/g, "");

  for (var i = 0; i < text.length; i++) {
    var letter = document.createElement("span");
    letter.style.display = "inline-block";
    letter.style.position = "absolute";
    letter.appendChild(document.createTextNode(text.charAt(i)));
    node.parentNode.insertBefore(letter, node);

    var positionRatio = i / (text.length - 1);
    var textWidth = letter.clientWidth;

    var indent = 100 * positionRatio;
    var offset = -textWidth * positionRatio;
    letter.style.left = indent + "%";
    letter.style.marginLeft = offset + "px";

    //console.log("Letter ", text[i], ", Index ", i, ", Width ", textWidth, ", Indent ", indent, ", Offset ", offset);
  }

  node.parentNode.removeChild(node);
}

function Justify() {
  var TEXT_NODE = 3;
  var elem = document.getElementById("character_justify");
  elem = elem.firstChild;

  while (elem) {
    var nextElem = elem.nextSibling;

    if (elem.nodeType == TEXT_NODE)
      SplitText(elem);

    elem = nextElem;
  }
}
#character_justify {
  position: relative;
  width: 20%;
  margin: 0;
  padding: 0;
}

#character_justify * {
  margin: 0;
  padding: 0;
  border: none;
}
<body onload="Justify()">
  <p id="character_justify">
   LOREM IPSUM<br>DOLOR<br>SIT AMET
  </p>
</body>

【讨论】:

  • 谢谢,但是这么小的事情代码太多了
  • @qadenza 进入浏览器渲染引擎的 C/C++ 代码量......可能没有更简洁的解决方案了。
猜你喜欢
  • 2023-04-06
  • 2011-05-20
  • 2015-10-07
  • 2012-02-28
  • 2011-07-25
  • 1970-01-01
  • 2019-08-25
  • 2014-07-24
  • 1970-01-01
相关资源
最近更新 更多