我有几个divs都被设计为内联块,因此彼此相邻排成一排.这些div的大小max-width为140px,并包含导致它们的宽度变化到该大小的文本.
正如max-width你所期望的那样,在这个小提琴中展示的文字比财产更宽.问题是它似乎也迫使它的容器div停留在max-width,即使包装文本在技术上不需要那么多空间.
有没有跨浏览器,HTML/CSS的方法,一旦文本换行,将这些块"收缩包装"到它们的最小宽度?我知道我可以用适当放置的<br>s 强制它,但这些块应该包含用户输入的文本.
.block {
display: inline-block;
vertical-align: top;
max-width: 140px;
background-color: lightgrey;
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
而不是max-width: 140px,考虑width: min-content。
CSS
.block {
display: inline-block;
vertical-align: top;
/* max-width: 140px; */
background-color: lightgrey;
text-align: center;
/* new */
width: min-content;
padding: 0 5px;
}
Run Code Online (Sandbox Code Playgroud)
演示:https : //jsfiddle.net/ex4n8m49/2/
注意:在实施min-content检查前缀要求和浏览器支持之前。
正如您所要求的,我不确定是否只有 CSS 解决方案。如果您决定尝试 JavaScript,以下帖子的公认答案可能对您有所帮助:
@BoltClock在/sf/answers/866451841/上解释了这个问题
您唯一的选择是JavaScript.
您可以通过缩小每个div宽度直到其高度变化来实现:
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';
}
}Run Code Online (Sandbox Code Playgroud)
.block {
display: inline-block;
vertical-align: top;
max-width: 140px;
background-color: lightgrey;
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)