Look, it’s all well and good that CSS has a hyphens
property. The problem is, that property is really dumb. It’s all-or-nothing, with no rhyme or reason to whether a word absolutely needs to be hyphenated. It will literally hyphenate any and every multi-syllable word at the end of a line.
You really almost never want that.
In my particular case, I’m looking at a very specific situation. Specific, but I am guessing probably the most common situation where a web developer wants a browser to hyphenate words: words in large headings that are too long to fit on a line. What I mean here is individual words that are by themselves too long to fit on a line, typically in a mobile browser, in headings with large or extra-wide fonts.
There are proposals to improve this, but there is currently nothing with broad browser support. So I invented my own.
This is a crafty little combination of CSS and JavaScript. (OK, technically it’s jQuery, but you could reasonably adapt this to vanilla JavaScript if that’s your thing. Since I’m deeply immersed in the jQuery world of WordPress, I just went with jQuery because it’s simpler for me that way.)
The first thing you need is a special CSS class for hyphenation. Since I only want it to apply on mobile devices, I gave it a logical name, and defined it in my CSS media query for the mobile breakpoint:
@media screen and (max-width: 782px) { .hyphenate-on-mobile { -webkit-hyphens: auto; hyphens: auto; } }
OK, with that set up, then we just need a little jQuery function to determine where it’s going to be applied. I want it to get added automatically to any h1
, h2
, h3
or h4
tag. (I’m skipping h5
and h6
because they’re small enough text that we shouldn’t need it.) I also made the somewhat arbitrary decision to set the minimum word length at 15 letters. This is something you may need to adjust based on your font size. Here’s the jQuery:
jQuery('h1, h2, h3, h4').each(function() { var words = jQuery(this).text().split(' '); var i = 0; var hyphenate = false; while (i < words.length) { if (words[i].length >= 15) { hyphenate = true; break; } i++; } if (hyphenate) { jQuery(this).addClass('hyphenate-on-mobile'); } });
And then you just want to make sure that jQuery gets fired off when the page loads. It works!