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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With