Can I break words only at 50% using css? Is it possible?
Instead of
longwor
d
doesn't long
word
look better?
What's the alternative?
Update: So maybe we can auto <wbr>
with js on the really long words.
Can I break words only at 50% using css? Is it possible?
Instead of
longwor
d
doesn't long
word
look better?
What's the alternative?
Update: So maybe we can auto <wbr>
with js on the really long words.
In CSS hyphens: auto
allows for automatic language-aware sensible hyphenation. Language is derived from the lang
property.
Compatibility varies with language and browser (not implemented at all in Chrome, sadly).
You may also find use for ­
which is a manual hyphenation clue. It is called a soft hyphen and is not visibly rendered, but merely suggests to the browser where a word may be broken.
Css tricks has a good writeup on the subject
Edit
As per your request in comments, I've made slight alterations to Resig's snippet, so that the pattern targets the full word and inserts the <wbr>
in the calculated middle, rather than always after the treshold length.
The only modification to the actual pattern is to continue the search, and not stop after the threshold. I've also done away with the grouping brackets, as we'll only be using the full word:
RegExp("\\w{" + num + "}\\w+", "g")
We then find the center of the word (c = Math.floor(all.length/2)
) and insert a browser hint at that point. I added a parameter to indicate whether wbr
or shy
should be used. The latter renders as a hyphen when hyphenation is required, and the former does not.
all.substring(0,c) + (!!shy?'­':'<wbr>') + all.substring(c)
Note that for word lengths greater than num*2
, the individual parts will also exceed the treshold. To get around this, I've simply added recursion:
function wbr(str, num, shy) {
return str.replace(RegExp("\\w{" + num + "}\\w+", "g"), function(all){
var c = Math.floor(all.length/2);
return wbr(all.substring(0,c) + (!!shy?'­':'<wbr>') + all.substring(c),num,shy);
});
}
I would suggest using the Hyphenator library, as the hyphens: auto
CSS property is not supported in the Chrome and Android Browser.
To use this library follow these simple steps:
Download the recent version of Hyphenator.js
Add hyphenate
classes to the elements, set lang
and add the Hyphenator.js <script>
.