MAT MARTIN | Code – Prevent Widows and Orphans in Fluid Width Web Layouts

13 July, 2017, 09:57 | Blog · Creating Content · Resources

Code - Prevent Widows and Orphans in Fluid Width Web Layouts
Code - Prevent Widows and Orphans in Fluid Width Web Layouts

For a recent web project I have been looking for a way to prevent widows and orphans (of the single word variety) in paragraph text. I was wondering if it was even possible to do while retaining responsive standards, where line length is fluid.

As a general rule, laying out type online (especially in responsive designs with containers of fluid width) is not the same as doing so in print. The natural flow of text and the variety of possible browser/device/screen/user combinations mean that some of the more precise rules and traditions of typesetting need to cede to practicality, usability and legibility. There are some cases though in which we do need to do this, e.g. a site for a copy writing service, an online emulation of page print, etc.

Widows and orphans are those words which get pushed onto new lines or over columns and page breaks by themselves, and they are considered bad typographic practice. Ilene Strizver explains this concisely in her article at fonts.com:

A widow is a very short line – usually one word, or the end of a hyphenated word – at the end of a paragraph or column. A widow is considered poor typography because it leaves too much white space between paragraphs or at the bottom of a page. This interrupts the reader’s eye and diminishes readability. Fix them by reworking the rag or editing the copy.

Like a widow, an orphan is a single word, part of a word or very short line, except it appears at the beginning of a column or a page. This results in poor horizontal alignment at the top of the column or page. The term “orphan” is not as commonly used as “widow,” but the concept is the same, and so is the solution: fix it!

I eventually found the way to prevent widows and orphans in a fluid-width situation in the form of a beautifully simple sideways approach to the problem from Tom Elliott on WebDevDoor. His suggestion was to include a short snippet of js which scans all paragraph text on a site and replaces the space between the last two words in each case with   – causing the page to read it as one and break the line one word earlier.


<script type="text/javascript">
  $('p').each(function(){
    var string = $(this).html();
    string = string.replace(/ ([^ ]*)$/,'&nbsp;$1');
    $(this).html(string);
  });
</script>

This might not be something to use as standard without thinking about it appropriateness to the project (what ever is?) but it certainly could be a useful tool in some cases. Call it in the header or footer of your template(s) and watch the line breaks line up. For more specific usage (target only <h2> and <p> text in a specific <div>, for example), head over to Tom’s original post.