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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With