Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to width-wise shrink-wrap content that spans more than one line?

Tags:

javascript

css

If I have an element contained in a box:

+-------- box --------+
| *------------*      |
| | small text |      |
| *------------*      |
+---------------------+

display: inline-block does the trick of shrink-wrapping it just fine. However, if the content spans more than one line because of the constrained width, it fails to shrink-wrap the element.

+-------- box --------+
| *-----------------* |
| | this does not   | |
| | shrink          | |
| | appropriately   | |
| *-----------------* |
+---------------------+

Is there any way of producing the desired result seen below?

+-------- box --------+
| *---------------*   |
| | this does not |   |
| | shrink        |   |
| | appropriately |   |
| *---------------*   |
+---------------------+

Here is a fiddle showing the two cases: http://jsfiddle.net/urLa8jvc/2/ and a solution where I manually break the line at the correct place to show the desired outcome. A CSS solution is preferred, but javascript is also acceptable.

like image 906
Christian Sonne Avatar asked Sep 12 '14 12:09

Christian Sonne


1 Answers

I'd really much prefer the solution to be CSS, but for now I've written this "hack" that does the trick using javascript: http://jsfiddle.net/86khx8kf/2/

var nodes = document.querySelectorAll(".node");
for (var nidx = 0; nidx < nodes.length; nidx++) {
    var node = nodes[nidx];
    node.innerHTML = node.innerHTML.split(" ").map(function (word) {
        return "<span>" + word + "</span>";
    }).join(" ");
    var spans = node.querySelectorAll("span");
    var offsetLeft = -Number.MAX_VALUE;
    for (var sidx = 0; sidx < spans.length; sidx++) {
        var span = spans[sidx];
        if (span.offsetLeft <= offsetLeft) {
            node.insertBefore(document.createElement("br"), span);
        }
        offsetLeft = span.offsetLeft;
        span.outerHTML = span.innerHTML;
    }
    node.normalize();
}
like image 137
Christian Sonne Avatar answered Nov 18 '22 15:11

Christian Sonne