Preventing Widows in Post Titles

Avatar of Chris Coyier
Chris Coyier on (Updated on )

Widows, typographically speaking, are single words that awkwardly break down onto their own line. It looks uncomfortable, and it reads uncomfortable. Article titles are especially prone to this because of the large type / short line length, and look exceptionally awkward with a widow. For example on this blog:

In the long long ago, I used to use a WordPress plugin to deal with this. It was based on Typogrify, a little project to help make stuff like this easier to deal with on the web (automatically). Today that project has grown up and it’s now called WP-Typography. This plugin doesn’t just fix widows, but offers all kinds of things to help improve web typography, for example, automatically wrapping your ampersands in <span class=”amp”></span> so you can use the best ampersand available.

For some reason I had it in my head that I didn’t like using plugins like this. I think it’s because I used to have a “Save to Delicious” button. The technique this plugin uses to fix widows is to add a &nbsp; (non-breaking space) between the last two words of a chunk of text so that it is impossible to have widows. But then when someone used my Save to Delicious button, the &nbsp; would show up there right in the post title and look ugly and strange.

So when I started to get the itch to fix this problem again, I looked to JavaScript to help out instead of PHP, so that I could target the titles alone, not the WordPress function for displaying titles. (Updated August 2013, AJ Zane suggested testing to make sure title is more than one word, otherwise it gets removed.)

$("h2 a").each(function() {
  var wordArray = $(this).text().split(" ");
  if (wordArray.length > 1) {
    wordArray[wordArray.length-2] += "&nbsp;" + wordArray[wordArray.length-1];
    wordArray.pop();
    $(this).html(wordArray.join(" "));
  }
});
  1. Split the title into an array of words
  2. Join the last two words together with a non-breaking space
  3. Remove the last item of the array (now redundant)
  4. Replace the title with the array joined back together with spaces

Works great! Although now that I don’t have a “Save to Delicious” button directly on my blog anymore, I think I’ll revert back to using the more robust WordPress plugin to do this. I’m sure most of you would agree that using server-side technology for something like this is the smarter way to go. My theory on these social bookmarking buttons is, incidentally, that if you are already a user of a social bookmarking service like Delicious, you already know how to bookmark something. The browser tools you have available to do so offer a far nicer user experience than clicking the button on my post does anyway…

Other Techniques

David Walsh teamed up with me today and is offering up how to accomplish these widow-busting techniques with MooTools and with PHP.