I have several div
s that are all styled as inline-blocks, and therefore sit in a row next to each other. These divs have a max-width
of 140px, and contain text that cause them to vary in width up to that size.
As demonstrated in this fiddle, text that is wider than the max-width
property wraps, as you would expect. The problem is that it also seems to force its container div
to stay at the max-width
, even though the wrapped text doesn't technically require that much space.
Is there a cross-browser, HTML/CSS-only way to "shrink-wrap" these blocks to their smallest width once the text wraps? I'm aware that I can force it with appropriately placed <br>
s, but these blocks are supposed to contain user-entered text.
.block {
display: inline-block;
vertical-align: top;
max-width: 140px;
background-color: lightgrey;
text-align: center;
}
<div class="block">A single line</div>
<div class="block">Two distinctively different lines</div>
<div class="block">A somewhat egregious demonstrative amount of text</div>
@BoltClock explains the issue well at https://stackoverflow.com/a/12377883/3903374
Your only option is JavaScript.
You can do so by shrinking each div
's width until its height changes:
var d = document.querySelectorAll('.block'),
i, w, width, height;
for(i = 0; i < d.length; i++) {
width = d[i].offsetWidth;
height = d[i].offsetHeight;
for (w = width; w; w--) {
d[i].style.width = w + 'px';
if (d[i].offsetHeight !== height) break;
}
if (w < d[i].scrollWidth) {
d[i].style.width = d[i].style.maxWidth = d[i].scrollWidth + 'px';
} else {
d[i].style.width = (w + 1) + 'px';
}
}
.block {
display: inline-block;
vertical-align: top;
max-width: 140px;
background-color: lightgrey;
text-align: center;
}
<div class="block">A single line</div>
<div class="block">Two distinctively different lines</div>
<div class="block">A somewhat egregious demonstrative amount of text</div>
<div class="block">LongTextThatsWiderThanMaxWidth Loremipsumdolorsitamet,consecteturadipiscingelit</div>
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