I am looking for an HTML / CSS solution for the problem that we encountered on the site we are creating. I am happy to implement a JavaScript-based solution if necessary, but I would prefer it to be handled initially.
We have text-driven content that should be inside the selection, but wrap if it exceeds the available width. Behind the text is a background color with opacity.
When the text is short, due to the float, the container shrinks to the width of the text. When the text is long and the wrapper occurs, the container hangs with the maximum width, even if the text inside is wrapped up at the bottom, so there is a small part of the background color on the right side (which is not enough for the wrapped word) I want the container to collapse on the edge of the previous word so that it doesn't it looked like there was room for a wrapped word when it is very close.
HTML
<div> <p>Crack the Shutters Open Wide for Parkside Paradise</p> </div>
CSS
body div { background-color: #AAFF3B; max-width:80%; padding:20px; display:inline-block; float:left; } body p { display:inline-block; background-color: #FFAA3B; position: relative; float:left; white-space:pre-line; clear:left; }
Here is the JSFiddle: http://jsfiddle.net/nmuot8bm/3/
If you look at the third example, you will see a small number of additions on the right side of the orange window, where the word porter is wrapped from the bottom to a new line, but the orange container is still sitting at maximum width, despite the float. If line breaks are entered by content editors (for example, between vestibulum and porttitor in accordance with Example 4), then the container is dumped correctly.
What I think the container grows before the text wraps and the browser does not recalculate the width after packing?
Here is an image of my test case shown in JSFiddle: 
Here is an error image on an intermediate site (before highlighting JSFiddle): 
You can see that the text is wrapped, but the container did not crash, leaving a large gap in the background color.
nb We can emulate this by doing text-align:justify , but then the spacing between words is not consistent with the rest of the text on the site.
edit: I see that this question may be a duplicate. I swear I did research before I sent a message.
is max-width suitable for text?
CSS Width / Maximum Wrap Line Width?
Wrap text forces containing an element up to max-width
Reduce DIV to text wrapped to maximum width?
I think the general consensus / conclusion is that this is not possible without using short-term CSS, and I should use a JavaScript solution.
I have added a few examples to my JSFiddle: http://jsfiddle.net/nmuot8bm/6/ including a JavaScript solution from here: https://stackoverflow.com/a/166778/