Search code examples
htmlcssstringtextline-breaks

Avoid breaking line between two words when resizing


I have a string and I need it not to break two specific words in different lines. Example:

"Ask for it it when contracting until 2016/09/30 with T-2 Rate"

When I resize window and make it smaller there is a moment that it outputs:

"Ask for it it when contracting until 2016/09/30 with T-2 \n
Rate"

I would like T-2 + Rate to be always together. How to do it?


Solution

  • You use a nonbreaking space. The HTML entity for it is  . You'll probably want a non-breaking hyphen (‑) in T-2 as well:

    Ask for it it when contracting until 2016/09/30 with T‑2 Rate
    

    Example:

    var target = document.getElementById("target");
    var originalWidth = target.innerWidth || target.clientWidth;
    var width = originalWidth;
    tick();
    function tick() {
      width = width < 10 ? originalWidth : (width - 10);
      target.style.width = width + "px";
      setTimeout(tick, 400);
    }
    #target {
      display: inline-block;
      border: 1px solid #ddd;
    }
    <div id="target">Ask for it it when contracting until 2016/09/30 with T&#8209;2&nbsp;Rate</div>