CSS文本以字母间距对齐

时间:2010-12-04 18:10:02

标签: css justify letter-spacing text-justify

有没有办法使用CSS自动对齐使用字母间距的单词,每个单词在行中,使用CSS自定义宽度?

例如,“像这样的东西”看起来像这样:

"Something like this" would look something like this

是否有一种非突兀的方式将这种样式应用到我的文本中?我相信纯CSS没有这个选项(至少在3之前没有CSS版本,CSS3似乎有text-justify属性,但它还没有得到很好的支持),所以js解决方案也没问题。

10 个答案:

答案 0 :(得分:11)

这是一个可以做到的脚本。它不漂亮,但也许你可以破解它来满足你的需求。 (已更新以处理调整大小)

<html>
<head>
<style>
#character_justify {
    position: relative;
    width: 40%;
    border: 1px solid red;
    font-size: 32pt;
    margin: 0;
    padding: 0;
}
#character_justify * {
    margin: 0;
    padding: 0;
    border: none;
}
</style>
<script>
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;
    }
}

</script>
</head>
<body onload="Justify()">
<p id="character_justify">
Something<br/>
Like<br/>
This
</p>
</body>

答案 1 :(得分:5)

仅限css的解决方案是text-justify: distribute https://www.w3.org/TR/css-text-3/#text-justify,但支持率仍然很差。

使用text-align-last: justify并在字母之间添加空格的小型实验。

&#13;
&#13;
div{
	display:inline-block;
	text-align: justify;
	text-align-last: justify;
	letter-spacing: -0.1em;
}
&#13;
<div>
S o m e t h i n g<br>
l i k e<br>
t h i s
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:4)

我知道这是一个古老的话题,但是那天晚上我遇到了这个问题。并使用表找到了合适的解决方案。

每个字母都应放入<td> </td>我知道它看起来很乏味,但如果你想这样做,那就是一两句话,对吗?或者如果太多,你总是可以使用JS填充它。但是,这只是CSS和非常通用的解决方案。

使用字母间距可以正确分配字母。你应该玩它,取决于桌子的宽度。

#justify {
  width: 300px;
  letter-spacing: 0.5em;
}
<table id="justify">
  <tbody>
    <tr>
      <td>J</td>
      <td>U</td>
      <td>S</td>
      <td>T</td>
      <td>I</td>
      <td>F</td>
      <td>Y</td>
    </tr>
  </tbody>
</table>

See the example here

Crossbrowser安全,几乎没有什么不同。只是CSS。

我在My website中使用了英语和西班牙语。 我用西班牙语命名的字幕有一个额外的字母,它会超出宽度。使用上面解释的表格,它会自动分配到相同的宽度。手动间隔我必须为每种语言定义一个完整的条件来解决这个问题。

答案 3 :(得分:3)

这是使用我为此问题撰写的jQuery代码段的另一种方法:Stretch text to fit width of div

<强> DEMO

HTML:

<div class="stretch">Something</div>
<div class="stretch">Like</div>
<div class="stretch">This</div>

jQuery:

$.fn.strech_text = function () {
    var elmt = $(this),
        cont_width = elmt.width(),
        txt = elmt.html(),
        one_line = $('<span class="stretch_it">' + txt + '</span>'),
        nb_char = elmt.text().length,
        spacing = cont_width / nb_char,
        txt_width;

    elmt.html(one_line);
    txt_width = one_line.width();

    if (txt_width < cont_width) {
        var char_width = txt_width / nb_char,
            ltr_spacing = spacing - char_width + (spacing - char_width) / nb_char;

        one_line.css({
            'letter-spacing': ltr_spacing
        });
    } else {
        one_line.contents().unwrap();
        elmt.addClass('justify');
    }
};


$(document).ready(function () {
    $('.stretch').each(function () {
        $(this).strech_text();
    });
});

答案 4 :(得分:2)

也需要这个,所以我在一个简单易用的jquery-plugin中捆绑了建议的技术,你可以在这里找到:https://github.com/marc-portier/jquery-letterjustify#readme

它使用相同的程序,并添加了一些调整选项。 欢迎评论。

答案 5 :(得分:0)

同样,我知道这真的很老了,但为什么不在每个字母之间放一个空格然后text-align:justify?然后每个字母都被视为一个“字”并相应地证明

答案 6 :(得分:0)

我刚用表格的Tony B方法制作了一个JQuery脚本。 这是JSFiddle https://jsfiddle.net/7tvuzkg3/7/

此脚本创建一个包含连续每个char的表。这适用于完整的句子。 我不确定这是完全优化的。

&#13;
&#13;
justifyLetterSpacing("sentence");

function justifyLetterSpacing(divId) {

	// target element
	domWrapper = $('#' + divId).clone().html('');
	// construct <td>
	$('#' + divId).contents().each(function(index){
      // store div id to td child elements class
	  var tdClass = divId ;
      // split text 
	  $textArray = $(this).text().split('');
      // insert each letters in a <td>
	  for (var i = 0; i < $textArray.length; i++) {
        // if it's a 'space', replace him by an 'html space'
        if( $textArray[i] == " " )  {
            $('<td>')
                .addClass(tdClass)
                .html("&nbsp;&nbsp;")
                .appendTo(domWrapper);
        }// if it's a char, add it
        else{  
            $('<td>')
                .addClass(tdClass)
                .text($textArray[i])
                .appendTo(domWrapper);
        }
	  }
	});
    // create table
    table = 
    $( "<table id='"+divId+"'/>" ).append( 
        $( "<tbody>" ).append( 
            $( "<tr>" ).append( 
                ( domWrapper ).children('td') 
            ) 
        )
    );
    // replace original div
	$('#' + divId).replaceWith( table );
}	
&#13;
#sentence {
  width : 100%;
  background-color : #000;
  color : #fff;
  padding : 1rem;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sentence">LOREM IPSUM DOLOR</div>
&#13;
&#13;
&#13;

答案 7 :(得分:0)

找到了另一种通过纯CSS实现此目的的方法,a,您需要拼出单词。

在我的情况下,这是唯一可行的解​​决方案(有些字母带有类),而且在不使用hack的情况下,它还能在答案中产生最直接的右对齐。

.box {
  width: min-content;
  border: solid red;
}

.word {
  display: flex;
  justify-content: space-between;
}
<div class="box">
  <div class="word">
    <span>S</span>
    <span>o</span>
    <span>m</span>
    <span>e</span>
    <span>t</span>
    <span>h</span>
    <span>i</span>
    <span>n</span>
    <span>g</span>
    <span>&nbsp;</span>
    <span>w</span>
    <span>i</span>
    <span>c</span>
    <span>k</span>
    <span>e</span>
    <span>d</span>
  </div>

  <div class="word">
    <span>t</span>
    <span>h</span>
    <span>i</span>
    <span>s</span>
    <span>&nbsp;</span>
    <span>w</span>
    <span>a</span>
    <span>y</span>
  </div>

  <div class="word">
    <span>c</span>
    <span>o</span>
    <span>m</span>
    <span>e</span>
    <span>s</span>
  </div>
</div>

答案 8 :(得分:0)

我通常会尽量准时写出我的答案。这是完全相同的时间(10 年后)=)

myText.innerHTML = myText.textContent
    .split(/\s+/g)
    .map((line) => line.trim().split("").join(" "))
    .join("<br>");
#myText {
    display: inline-block;
    text-align: justify;
    text-align-last: justify;
    letter-spacing: -0.125em;
    font-family: sans-serif;
}
<div id="myText">Something like this</div>

答案 9 :(得分:-1)

text-align: justify有什么问题?我想我可能会误解你的问题。