title: Truncate string based on pixel width
body: <p>I'm trying to make a string fits in a determined area (<code>td</code>) without breaking line. The problem is: It needs to ... </p>
  
  <ul>
  <li>Fit while resizing</li>
  <li>Fit in <code>N</code> kinds of resolution</li>
  <li>Add <code>...</code> at the end when needed (and don't when not needed)</li>
  <li>Accept the change of <code>font-size</code>, <code>font-weight</code>, and <code>font-family</code></li>
  </ul>
  
  <hr>
  
  <p>Based on the answers on <a href="https://stackoverflow.com/questions/895888/truncate-text-with-jquery-based-on-pixel-width">Novon's question</a>, I made the following code:</p>
  
  <p><strong>CSS</strong> <em>(// Just adding some styles to break the line)</em></p>
  
  <pre><code>.truncated { display:inline-block; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  </code></pre>
  
  <p><strong>jQuery</strong> <em>(// Find all td that contains a <code>.truncated</code> element. Getting the real width (by removing the content and adding it again) of the <code>td</code>. Applying, if needed, minWidth on the <code>td</code>)</em></p>
  
  <pre><code>jQuery('.truncated').closest('td').each(function() {
      var text = jQuery(this).text();
      var widthOriginal = jQuery(this).width();
      var widthEmpty = jQuery(this).text('').width();
      jQuery(this).text(text);
      if(widthOriginal &gt;= widthEmpty){
          var width = (parseInt(widthEmpty) - 10) + 'px';
          jQuery(this).css('maxWidth', width);
          jQuery(this).text(text + '...');
      }
  });
  </code></pre>
  
  <p>the result (as expected from the above code) is:</p>
  
  <p><img src="https://i.stack.imgur.com/sSA5Z.png" alt="result"></p>
  
  <p>but it should be:</p>
  
  <p><img src="https://i.stack.imgur.com/aNGKq.png" alt="how it should be"></p>
  
  <hr>
  
  <p>I was thinking, maybe try to find the first <code>line</code> of the string and remove the rest but didn't find a way to do that (and it's a lot of "workaround" for my taste). Is there a better way to do that?</p>