Basj
Basj

Reputation: 46463

Avoid unnatural word-break

I have a <h1> title with a long word, such as the following. The browser width depends on the device of course, but I've noticed that on one of my devices, it looks like this:

enter image description here

which is not a very nice word-breaking.

How to ask the browser to do "nicer" breakings instead?

Example: Internationali-sation or -tion or -on but not n alone in the next line.

Here is how to reproduce the problem (I've hardcoded 260px here just to reproduce what I've seen on my device, but this is not really hardcoded in my code):

.a { width: 260px; background-color: yellow; }
h1 { word-wrap: break-word; }
<div class="a">
<h1>Internationalisation</h1>
</div>

Upvotes: 3

Views: 334

Answers (3)

Jax-p
Jax-p

Reputation: 8531

You can manually insert soft hyphen &shy; which is visible only on break. It suggests a place where the browser might break that word. Its something like <wbr> but with hyphen. Something like this:

h1 { word-wrap: break-word; }
.small { width:260px; }
<h1 class="small">Internationali&shy;sation</h1>
<h1>Internationali&shy;sation</h1>

There are a lot of problems with automatic word breaking which usually depends on browser dictionary (hyhphens can be used) or external scripts. You can also read more about it in another questions like Is it possible to enable auto-hyphenation in HTML/CSS?.

Upvotes: 5

Ivar
Ivar

Reputation: 6828

The <wbr> tag exists for this purpose.

The HTML <wbr> element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.

.a { width: 260px; background-color: yellow; }
h1 { word-wrap: break-word; }
<div class="a">
<h1>Internationali<wbr>sation</h1>
</div>

Alternatively you can also add a zero-width space to the word, though that might cause odd behavior when trying to copy the string. (We get some questions here on Stack Overflow where code doesn't work because it contains a hidden zero-width space.)

Upvotes: 4

Squiggs.
Squiggs.

Reputation: 4474

Well you could prevent breaking altogether...

.a { width: 260px; background-color: yellow; }
h1 { white-space: nowrap; }
<div class="a">
<h1>Internationalisation</h1>
</div>

Or. set spans inside your content to denote where breaking should occur. This is a big ass word, not two separate words so the browser is clueless unless you educate it

.a { width: 260px; background-color: yellow; }
h1 { word-wrap: break-word; }
h1 span { display: inline-block; }
<div class="a">
<h1>International<span>isation</span></h1>
</div>

Upvotes: -1

Related Questions