CSS文本对齐与字母间距 [英] CSS text justify with letter spacing

查看:229
本文介绍了CSS文本对齐与字母间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法自动使用字母间距,使用字符间距,在其行,使用CSS定义的宽度,使用CSS?

Is there a way to automatically justify words using letter spacing, each in its row, to a defined width, using CSS?

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

For example, "Something like this" would look, well, something like this:

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

Is there a non-obtrusive way to apply such styling to my text? I believe pure CSS doesn't have this option (at least not with CSS versions before 3, CSS3 seems to have a text-justify property, but it's not well supported yet), so js solutions would be fine also.

推荐答案

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

Here's a script which can do it. It isn't pretty, but maybe you can hack it to meet your needs. (Updated to handle resizing)

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

这篇关于CSS文本对齐与字母间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆