21

Not the best title, but anyway...

I have an element with a max-width and some text.

If the text is longer than will fit on one line, I get this:

----------------------------
|My text here, hello       |
|everyone!                 |
----------------------------

In other words, it takes up the full max-width, but there's an empty space on the right due to the word moving down.

Is there any way to make it so that this happens instead?

---------------------
|My text here, hello|
|everyone!          |
---------------------
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592

4 Answers4

6

Not Possible by CSS Alone

According to BoltClock in this answer, it is not possible. The explanation makes sense. For the line wrap to occur to begin with, the line needs to reach the max-width setting. Once done, it wraps, but it does not reshrink because it is using that size for the calculation of the wrap.

As far as I know, this is still not possible.

Community
  • 1
  • 1
ScottS
  • 71,703
  • 13
  • 126
  • 146
  • [float doesn't work](http://jsfiddle.net/ght3C/11/) either. Remember it needs to be a single line of text. – Niet the Dark Absol Dec 02 '12 at 20:50
  • @Kolink--unless I am missing something, `float` (and all the others noted) work just fine in collapsing to the width of the text (whether one line or not). Is that not what you want? Look at [this fiddle](http://jsfiddle.net/ght3C/14/) with a super wide `max-width`. It collapses the last four div's for me on IE8/9, Firefox 17, and Chrome 23... ahhh, but not if small enough if the line wraps [like this](http://jsfiddle.net/ght3C/17/); that's what you are wanting, isn't it? – ScottS Dec 03 '12 at 02:41
  • That's exactly what I'm after ;) If a line is too long to fit. – Niet the Dark Absol Dec 03 '12 at 04:22
  • @Kolink--at present there only appears to be a partial (not fully cross browser) to the issue. See my update. – ScottS Dec 03 '12 at 14:35
  • @zooted: thanks. I deleted that portion because you were right, and to my knowledge, it is still not possible. – ScottS Mar 04 '16 at 05:39
3

I’ve yet to find a method that does not require the use of both a wrapper element and JavaScript, but it’s possible that this one suits your needs.

<div id="example">
    <span id="content">My text here, hello everyone!</span>
</div>​​​​​​​​​​​​​​​​​​​​​
​var content = document.getElementById("content");

content.parentNode.style.width = content.offsetWidth + "px";​​​​

a working example

1

Use the above solution, but on the inner element set display: table-caption, and DON'T set max-width: 0px. This will include safari support (as well as Firefox 17 and IE8/9 and Chrome)

0

Feel like word-break is what you need http://caniuse.com/word-break although it is CSS3 new property with not such a wide support yet

dmi3y
  • 3,482
  • 2
  • 21
  • 32