0

I have a request from our content & design teams to not let paragraphs of text end with an "orphan word" - a single word on the last line of text that has wrapped to multiple lines. The designer's solution is to cheat the margins to, say, +/- 5% to see if we can get the word to move to the previous line or get a word to join it on the last line. That is easy to do by hand but of course we need it to work in code so that it works with different sizes, languages, etc.

What is the best way to detect how many words are in the last line of a wrapped text block? I assume this would involve breaking the string into words, each in their own span or something...?

Thanks in advance!

Dave Vronay
  • 625
  • 7
  • 22
  • take a look here: https://stackoverflow.com/questions/783899/how-can-i-count-text-lines-inside-an-dom-element-can-i – Mario Abbruscato Jun 25 '21 at 01:25
  • you need to know: the width of the element container , how many words you have, font size , paddings, margins . then you can compute the number of spaces between words so that the words in a line are at least two. – Mario Abbruscato Jun 25 '21 at 01:43

1 Answers1

0

Clearly I was overthinking this. Someone mentioned that for the use case above, it is sufficient to just replace the space between the final two words with a non-breaking space. (&nbsp). Duh!!

example in action:

<div>This div will not have orphaned&nbsptext</div>
Dave Vronay
  • 625
  • 7
  • 22