Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

html - Wrapping text forces containing element to max-width

I have several divs 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...