How to Avoid One Word on the Last Line with CSS

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

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

 

<p>Such and such doesn't have to be difficult. Such and such product makes it 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

How to avoid orphan word on a line with css?

A quick and easy way to prevent two words from breaking is to insert a non breaking space   between the words

ECSTASY OF EXISTENCE FIRMING ANTIOXIDANT BODY SERUM

It won't be visible on the front end but those words will stay together even if there enough space for just one of them.

<h2>ECSTASY OF EXISTENCE FIRMING ANTIOXIDANT BODY SERUM</h2>

Make the last line of each paragraph shorter than the rest

This is not available as a feature of CSS, however you can work around this limitation using CSS's ::after pseudo-element like this:

p {

text-align: justify;

text-align-last: left;

}

p::after {

content: '––––––––––––––––––––';

visibility: hidden;

white-space: nowrap;

}
<p style='width: 380px'>

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

sed do eiusmod tempor incididunt ut labore et dolore

magna aliqua. Ut enim ad minim veniam, quis nostrud

exercitation ullamco laboris nisi ut aliquip ex ea

commodo consequat. Duis aute irure dolor in

reprehenderit in voluptate velit esse cillum dolore eu

fugiat nulla pariatur. Excepteur sint occaecat cupidatat

non proident, sunt in culpa qui officia deserunt mollit

anim id est laborum.</p>

Stop word-wrap dividing words

use white-space: nowrap;. If you have set width on the element on which you are setting this it should work.

update -
rendered data in Firefox
alt text



Related Topics



Leave a reply



Submit