Yuval Adam
Yuval Adam

Reputation: 165242

CSS word-spacing specification

Are there any characters that CSS word-spacing does not break on?

For example suppose I give my element a large word-spacing size (equal to element width), such that it breaks on each word. So for this:

<div class="break">THIS BREAKS ON EACH LINE</div>

I'll get:

---------
| THIS
| BREAKS
| ON
| EACH
| LINE
|--------

Is there any character I can use that will not break lines. For example:

<div class="break">THIS BREAKS & EACH LINE</div>

I want no break after the ampersand:

---------
| THIS
| BREAKS
| & EACH          <<<--- Here
| LINE
|--------

Upvotes: 0

Views: 396

Answers (4)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201568

In general, white-space affects spacing between “words” in a technical sense: a word is a maximal sequence of non-whitespace characters. So, in effect, it affects all whitespace (spaces, tabs, newlines). However, fixed-width space characters such as &ensp; are not counted as whitespace, so you can write

THIS BREAKS &&ensp;EACH LINE

if you do not want the spacing between “&” and “EACH” to expand. This is not completely safe, though, since browsers may some day treat characters differently. They already changed the way &nbsp; is handled; it used to be “non-stretchable” but isn’t any more.

So the safe way is really

THIS BREAKS <span class=nows>& EACH</span> LINE

with CSS

.nows { word-spacing: 0 }

Preventing line breaks is a different question, often asked and answered at SO. Using the safe way above, you could just use a no-break space instead of a normal space:

THIS BREAKS <span class=nows>&&nbsp;EACH</span> LINE

Upvotes: 1

Yuval Adam
Yuval Adam

Reputation: 165242

I found a decent workaround using the "thin non breaking space" character (&#8239;) which behaves properly.

http://jsfiddle.net/RJ6KW/4/

Upvotes: 2

SW4
SW4

Reputation: 71150

You can use &nbsp; (non-breaking space) to prevent a break...however this will maintain your word spacing.

Your best bet would be to throw a bit of jQuery in there, a la:

CSS

.break{
    word-spacing:50px;
    width:50px;

}

HTML

<div class="break">THIS BREAKS ON & EACH LINE</div>

jQuery

var txt = $('.break');
var ls=txt.css('word-spacing');
txt.html(txt.text().replace(' & ', '<span style="margin:0 -'+ls+' 0 0;"> &&nbsp;</span>'));

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Use non-breaking space &nbsp; like this:

<div class="break">THIS BREAKS &&nbsp;EACH LINE</div>

see this demo

Upvotes: 0

Related Questions