Berry Blue
Berry Blue

Reputation: 16482

div contenteditable and word-wrapping with span elements

When I have span tags in a contenteditable div the word wrapping changes. Here is a fiddle. http://jsfiddle.net/knpB9/

<div contenteditable="true" style="width:168px; border:1px solid black;">aaaaaaaa-bbbbbbbb-ccccccc</div>
<br>
<div contenteditable="true" style="width:168px; border:1px solid black;">aaaaaaaa-bbbbbbbb-<span style="color:red;">ccccccc</span></div>

How do I keep the word wrapping the same regardless of the html tags?

Upvotes: 0

Views: 3621

Answers (1)

Mathijs Flietstra
Mathijs Flietstra

Reputation: 12974

If you want to preserve the normal line breaks you can set the span to display: inline-block;.

Here's a jsFiddle.

This bit of CSS does the trick if you don't care about lines breaking in the middle of a word:

div
{
    white-space: pre;
}

Here's a jsFiddle.

Have a look here to read up on how and why it works the way it does.

Update

The reason why it wraps the way it does in you last jsFiddle is because the hyphens provide the browser with a soft wrap opportunity. You could replace those with a non-breaking hyphen or &#8209; and it should wrap the as expected again. You could write some JS that would capture every keypress on the contenteditable element, then cancels its normal behaviour if the hyphen key is pressed, and inserts the non-breaking hyphen instead of the normal hyphen

Here's a jsFiddle.

Upvotes: 2

Related Questions