Question

How to break a word and keep it on the same line with CSS?

Let's say I have the following paragraph tag:

<p>10 andSomeQuiteLongWord</p>

If I use word-break: break-word or overflow-wrap: anywhere, the word breaks as expected but also gets to a new line, like this:

|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾|
|10               |
|andSomeQuiteLongW|
|ord              |
|_________________|

I would like to display it as such:

|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾|
|10 andSomeQuiteLo|
|ngWord           |
|_________________|

Is there a way to achieve this?

 3  61  3
1 Jan 1970

Solution

 3

word-break using break-all should do it:

div {
  width: 100px;
  background: red;
  word-break: break-all;
}
<div>
  10 andSomeQuiteLongWord
</div>

2024-07-15
j08691

Solution

 1

Apply word-break: break-all; but only on the word you want to break:

div {
  width: 100px;
  outline: solid 1px blue;
}
<div id="div">
  10000 <span style="word-break: break-all;">andSomeQuiteLongWord</span>
</div>
<input type="range" min="25" value="100" oninput="div.style.maxWidth = this.value + 'px'">

2024-07-15
imhvost

Solution

 0

Just in case you don't know it: You can use the &shy; entity (called "soft hyphen") in the HTML code to enable breaks only at certain points which will only be applied if necessary. If you use several of them in one long word, you can get different results depending on the contents around that word:

div {
  border: 1px dotted #555;
}
div:nth-of-type(1) {
  width: 200px;
}
div:nth-of-type(2) {
  width: 150px;
}
div:nth-of-type(3) {
  width: 100px;
}
<div>
  10 and&shy;Some&shy;really&shy;Long&shy;Word
</div>
<div>
  10 and&shy;Some&shy;really&shy;Long&shy;Word
</div>
<div>
  10 and&shy;Some&shy;really&shy;Long&shy;Word
</div>

2024-07-15
Johannes