word-wrap: break word; fix or alternative

Viewed 1374

With word-wrap: break-word; if the word is going to break anyway, I dont want a line-break first, it is useless and ugly. How to avoid that?

Example:

Given a div with word-wrap: break-word; and a width equivalent to those 23 "x" characters like so:

xxxxxxxxxxxxxxxxxxxxxxx


The div innerHTML is "xx xxxxxxxxxxxxxxxxxxxxxxxxxxxx" like so:

<div>xx xxxxxxxxxxxxxxxxxxxxxxxxxxxx</div>   


This is how the innerHTML of the div is displayed vs how it is wanted respecting the 23 "x" width.

What happens:
xx
xxxxxxxxxxxxxxxxxxxxxxx
xxxxx

What I want:
xx xxxxxxxxxxxxxxxxxxxxx
xxxxxxxx



word-break: break-all; and similar or more recent attributes are not a solution to the problem. I dont want words that can avoid breaking to break. I only want words with a width superior than the container width to break BUT without line-break first like with word-wrap: break-word; because it is simply useless and ugly.

3 Answers

In complement of the answer of MaxiGui. You can also use non-breaking space &nbsp; in your HTML (or replace space with non-breaking space with JS). But I think it's better to use of word-break: break-all;

EDIT : hyphens do all the job https://developer.mozilla.org/en-US/docs/Web/CSS/hyphens

As @Sfili_81 mentionned it

something like word-break: break-all;

Here you go

var txt = document.getElementById("demo").innerHTML;

var dataArr = txt.split(' ');

var paragraph = document.getElementById("demo");
var finalString = "";
for (var i = 0; i < dataArr.length; i++){
    if (dataArr[i].length > 6 ) {
      finalString = finalString + " <span>"+ dataArr[i]+"</span>"; 
  }
  else{
    finalString = finalString + " " + dataArr[i];
  }
}

paragraph.innerHTML = finalString;
div{
  width:50px;
  background: red;
 
}
span{
  word-break:break-all;
}
<div id="demo">test teeeeeeeeeeest test test test</div>

PS: I still flagged the question as duplicate from: How to force a line break in a long word in a DIV?

EDIT

As break-all is also breaking the whole text / word and break-word is letting a white space / gap before the long word, then it is not adapting. So only solution is JS. In this example, We are injecting span element to text with length over 6.

An alternative solution using jQuery:

HTML:

<div id="demo">xx xxx xxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxx</div>

JS:

$(document).ready(function() {
  var words = $('#demo').text().split(' ');
  $('#demo').empty();
  $.each(words, function(i, v) {
    $('#demo').append($('<span>').text(v));
  })
});

CSS:

#demo {
  width: 100px;
  border: 1px solid #F00;
  word-wrap: wrap;
  word-break: break-all;
}

#demo span {
  display: inline-block;
  border: 1px dashed #00F;
  word-wrap: break-word;
  margin-right: 2px; /* add the space back */
}

This solution is slightly better than the accepted one, as it does not require a hardcoded value of the words' length.

JSFiddle demo

Related