css breaking words only if no spaces
Asked Answered
M

1

6

I have this code:

.mydiv {
  display: table;
  table-layout: fixed;
  width: auto;
  max-width: 448px;
  height: 56px;
}

.mydiv span {
  display: table-cell;
  vertical-align: middle; 
  overflow: hidden;
}
<div class="mydiv">
  <span></span>
</div>

This works fine most of the time as, by default, if the text is longer than a line, the line breaks at the closest space and words are never divided into half-words. Good.

But, in the only case where a sentence has no spaces (this is never supposed to happen but people are people), the interface will break and the long word will then remain on one line.

IS there a way to prioritize css so that, IF there are spaces, the sentence is cut without cutting the words (word-wrap: break-word;) but IF the word is bigger than a line, the line breaks, cutting the word (word-break: break-all;) to avoid a visual disaster. In that order.

So far, if I use "word-wrap: break-word;", one long word will remain on one line, whatever its length and if I use "word-break: break-all;" the words will then be broken even if there are spaces available before. none of these standard solution are helping.

Any help would be appreciated.

I would like a CSS solution, preferably, but if it's not possible, a JS/jQuery solution would do too.

PS: I need the div to have an auto width with a max-width and I need the span to remain a table-cell.

Monochloride answered 9/1, 2018 at 6:39 Comment(0)
X
16

You can do it with the word-wrap: break-word but you have to set the value of the width property to 100% to enable responsiveness:

.mydiv {
  display: table;
  table-layout: fixed;
  width: 100%; /* responsiveness */
  max-width: 448px;
  height: 56px;
  border: 1px solid; /* just for demo */
}

.mydiv span {
  display: table-cell;
  vertical-align: middle; 
  overflow: hidden;
  word-wrap: break-word; /* added */
}
<div class="mydiv">
  <span>looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word</span>
</div>
<br>
<div class="mydiv">
  <span>short word ... short word ... short word ... short word ... short word ... short word ... short word ... short word ...</span>
</div>
Xenomorphic answered 9/1, 2018 at 6:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.