0

display:inline-block is supposed to shrink a div horizontally to no more than the space required to display the div, but when the div is multiline, then the div expands horizontally to 100%, resulting in some padding at the end of the lines. How can I get the div to shrink to the end of the longest line?

div {display:inline-block; background:lightblue; border:1px solid red}
<div>
When in the course of human events it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.
</div>

enter image description here

  • _“How can I get the div to shrink to the end of the longest line?”_ - you can’t. – 04FS Oct 01 '20 at 11:23
  • 1
    Possible duplicate of https://stackoverflow.com/questions/41389292/display-inline-block-does-not-make-width-as-small-as-possible-with-wrapped-cont – 04FS Oct 01 '20 at 11:24
  • a workaround is to consider text-algin:justify – Temani Afif Oct 01 '20 at 11:24
  • https://stackoverflow.com/questions/450903/how-can-i-make-a-div-not-larger-than-its-contents/451074#451074 – 04FS Oct 01 '20 at 11:24
  • @04FS The duplicate you linked to shows that it _is_ possible. – Sean Oct 01 '20 at 11:27
  • @Sean it really depends on specifics. The examples there use only two words as element content, and it breaks after the first, longer one. But apply that same `display: table-caption` solution here, and the element will get quite narrow, probably not what OP wants here. – 04FS Oct 01 '20 at 11:31
  • @04FS it's also possible using javascript. The point being, that initial comment isn't helpful. – Sean Oct 01 '20 at 11:38
  • @sean yes, but this question was tagged `css` only, so we should assume OP is looking for a pure CSS solution first of all. – 04FS Oct 01 '20 at 11:39
  • (1) I did look for other posts before posting but none that I found seemed like an exact match for my problem. (2) I didn't tag this post with JS b/c it didn't occur to me that a CSS-only solution isn't possible and a JS solution is. (3) text-align:justify is a good enough solution, thank you. (4) The JS solutions use JQuery which I can't follow (I don't use JQ and wouldn't load a library just to solve this problem), but again, text-align:justify is good enough for me for now. (5) I'm realizing my question was poorly worded. The problem is unrelated to display:, unstyled DIVs have same prob – Michael Bluejay Oct 02 '20 at 01:39

0 Answers0