Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent having just one hanging word on a new line in an HTML element?

I'm building a simple webpage with some marketing content. One thing I don't like is that if a line of text is too long, it will wrap onto the next line, which is fine, but it often wraps in such a way that there is only one word on the new line, which is just bad news from a design standpoint.

Such and such doesn't have to be difficult. Such and such product makes it
easy

What can I do to dynamically ensure at least two words on each hanging line?

Such and such doesn't have to be difficult. Such and such product makes
it easy

like image 837
Joe Davison Avatar asked Aug 12 '15 20:08

Joe Davison


People also ask

How do I stop a word break in HTML?

How to Prevent Word Wrap on a Web Page: HTML Method. If you only have the one-off instance of two or more words that you want to force the browser to keep on a single line, the easiest way is to use the non-breaking space character, "   ", to separate those words instead of a normal space.

How do I make text stay on the same line in HTML?

You can force the content of the HTML <div> element stay on the same line by using a little CSS. Use the overflow property, as well as the white-space property set to “nowrap”.


3 Answers

The simple solution is to use a non-breaking space between the last two words at the end of a paragraph.

&nbsp;

<p>Such and such doesn't have to be difficult. Such and such product makes it&nbsp;easy</p>

This could get tedious if you have a lot of content and especially if it is business controlled. In that case you may be able to find a library or write a solution that automatically inserts the non-breaking space between the last two words of every paragraph for you.

Try this: https://matthewlein.com/tools/widowfix

like image 112
koga73 Avatar answered Oct 20 '22 04:10

koga73


EDIT: The best answer is much cleaner -- you should probably use that instead. I'm leaving my answer up because it does work and it has some value for weird cases (e.g. if you're using a dash instead of a space, if you don't want to use &nbsp;, etc).


Here's a neat little solution. Create a CSS class like this:

.nobr { white-space:nowrap; }

Any element with the class "nobr" will not be allowed to wrap white-space (spaces, tabs, etc) onto new lines. So just surround the last two words of your text with a span.nobr.

<p>Such and such doesn't have to be difficult. Such and such product makes <span class="nobr">it easy</span></p>
like image 13
Hayden Schiff Avatar answered Oct 20 '22 04:10

Hayden Schiff


I would use a <nobr>last two words.</nobr> tag.

This also gives the benefit of not cutting off any HTML flourishes you may be doing, eg:

<b>&ldquo;</b>Here's a big statement I don't want <nobr>cutting off<b>&rdquo;</b>.</nobr>
like image 5
Kevin Sedgley Avatar answered Oct 20 '22 03:10

Kevin Sedgley