Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

max-width adjusts to fit text?

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

Upvotes: 23

Views: 11125

Answers (4)

ScottS
ScottS

Reputation: 72261

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.

Upvotes: 7

MrVerticalStack
MrVerticalStack

Reputation: 47

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)

Upvotes: 1

user1479055
user1479055

Reputation:

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

Upvotes: 4

dmi3y
dmi3y

Reputation: 3522

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

Upvotes: 0

Related Questions