简体   繁体   中英

Force two words to be always together in a line

I have this line:

Welcome to the nicest home 🚀

This line is inside a flex div width responsive width. When with is small enough, this happens

Welcome to the
nicest home 
🚀

Is there a way with which I can force home and to be always together? So in the example I would get

Welcome to the
nicest
home 🚀

As suggested in the comments, a non-breaking space will do the trick.

To include it in the HTML, we usually use the symbol code:  

(Drag the corner of the box to resize and test the example)

 div { display: block; resize: both; overflow: hidden; border: 1px solid #000; }
 <div>Welcome to the nicest home&nbsp;</div>

One method to achieve this would be to replace the last whitespace found in the string with a non-breaking space entity, &nbsp; .

You can use JS to do this to all elements you decorate with a given class:

 document.querySelectorAll('.no-orphans').forEach(el => { el.innerHTML = el.innerHTML.replace(/ (?=[^ ]*$)/i, "&nbsp;"); });
 p { width: 100px; }
 <p>Original:<br />Welcome to the nicest home </p> <p class="no-orphans">Corrected:<br />Welcome to the nicest home </p>

The only caveat here is that the end of the content within the .no-orphans element cannot be a HTML element, only a text node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM