将DIV收缩到包裹到其最大宽度的文本?

onl*_*ing 12 html javascript css

收缩包装div到一些文本是非常简单的.但是如果由于最大宽度(作为示例)文本换行到第二行(或更多行),那么DIV的大小不会缩小到新包装的文本.它仍然扩展到断点(在这种情况下为最大宽度值),在DIV的右侧产生相当大的余量.当想要使这个DIV居中以使包裹的文本看起来居中时,这是有问题的.它不会,因为DIV不会收缩到多行文本.一种解决方案是使用合理的文本,但这并不总是实用的,并且结果可能是可怕的,并且单词之间存在较大的间隙.

据我所知,没有解决方案可以将DIV缩小为纯CSS中的包装文本.所以我的问题是,如何用Javascript实现这一目标?

这个jsfiddle说明了它:jsfiddle.由于最大宽度,这两个词几乎没有换行,但是DIV不会缩小到新包装的文本,留下一个令人讨厌的右边缘.我想消除这一点并让DIV重新调整到包装文本大概使用Javascript(因为我不相信纯CSS中存在解决方案).

.shrunken {text-align: left; display: inline-block; font-size: 24px; background-color: #ddd; max-width: 130px;}

<div class="shrunken">Shrink Shrink</div>
Run Code Online (Sandbox Code Playgroud)

Syn*_*siS 6

这不是最漂亮的解决方案,但应该做到这一点.逻辑是计算每个单词的长度,并使用它来计算在被强制换行之前最适合的行是什么; 然后将该宽度应用于div.这里小提琴:http://jsfiddle.net/uS6cf/50/

示例html ...

<div class="wrapper">
    <div class="shrunken">testing testing</div>
</div>

<div class="wrapper">
    <div class="shrunken fixed">testing testing</div>
</div>

<div class="wrapper">
    <div class="shrunken">testing</div>
</div>

<div class="wrapper">
    <div class="shrunken fixed">testing</div>
</div>

<div class="wrapper">
    <div class="shrunken" >testing 123 testing </div>
</div>

<div class="wrapper">
    <div class="shrunken fixed" >testing 123 testing </div>
</div>
Run Code Online (Sandbox Code Playgroud)

和javacript(依赖于jQuery)

$.fn.fixWidth = function () {
    $(this).each(function () {
        var el = $(this);
        // This function gets the length of some text
        // by adding a span to the container then getting it's length.
        var getLength = function (txt) {
            var span = new $("<span />");
            if (txt == ' ')
                span.html('&nbsp;');
            else
                span.text(txt);
            el.append(span);
            var len = span.width();
            span.remove();
            return len;
        };
        var words = el.text().split(' ');
        var lengthOfSpace = getLength(' ');
        var lengthOfLine = 0;
        var maxElementWidth = el.width();
        var maxLineLengthSoFar = 0;
        for (var i = 0; i < words.length; i++) {
            // Duplicate spaces will create empty entries.
            if (words[i] == '')
                continue;
            // Get the length of the current word
            var curWord = getLength(words[i]);
            // Determine if adding this word to the current line will make it break
            if ((lengthOfLine + (i == 0 ? 0 : lengthOfSpace) + curWord) > maxElementWidth) {
                // If it will, see if the line we've built is the longest so far
                if (lengthOfLine > maxLineLengthSoFar) {
                    maxLineLengthSoFar = lengthOfLine;
                    lengthOfLine = 0;
                }
            }
            else // No break yet, keep building the line
                lengthOfLine += (i == 0 ? 0 : lengthOfSpace) + curWord;
        }
        // If there are no line breaks maxLineLengthSoFar will be 0 still. 
        // In this case we don't actually need to set the width as the container 
        // will already be as small as possible.
        if (maxLineLengthSoFar != 0)
            el.css({ width: maxLineLengthSoFar + "px" });
    });
};

$(function () {
    $(".fixed").fixWidth();
});
Run Code Online (Sandbox Code Playgroud)

  • 2021 年了——现在有 CSS 解决方案吗?我真的不想用js来做这个 (10认同)

Ber*_*eSF 6

我有点晚了,但我认为这个 CSS 代码对于遇到同样问题的其他用户很有用:

div {
  width: -moz-min-content;
  width: -webkit-min-content;
  width: min-content;
}
Run Code Online (Sandbox Code Playgroud)

  • 这会导致内容在每个可能的断点处换行,这不是相同的效果。 (13认同)