Skip to main content
2 of 3
Broke code into blocks of CSS, JavaScript and markup
Techek
  • 485
  • 5
  • 14

The code-snips below, "calculate" the width of the span-tag, appends "..." to it if its too long and reduces the text-length, until it fits in its parent (or until it has tried more than a thousand times)

CSS

div.places { width : 100px; } div.places span { white-space:nowrap; overflow:hidden; } 

HTML

<div class="places"> <span>This is my house</span> </div> <div class="places"> <span>And my house are your house</span> </div> <div class="places"> <span>This placename is most certainly too wide to fit</span> </div> 

JavaScript (with jQuery)

// loops elements classed "places" and checks if their child "span" is too long to fit $(".places").each(function (index, item) { var obj = $(item).find("span"); if (obj.length) { var placename = $(obj).text(); if ($(obj).width() > $(item).width() && placename.trim().length > 0) { var limit = 0; do { limit++; placename = placename.substring(0, placename.length - 3) + "..."; $(obj).text(placename); } while ($(obj).width() > $(item).width() && limit < 1000) } } }); 
Techek
  • 485
  • 5
  • 14