Rewriting file names according to the available screen space I created a function that rewrites file names according to the available space on screen:

@{
  var index = 0;
  foreach (var item in Model)
  {
  &lt;div class="gallery-item"&gt;
    &lt;a href="@item.Uri" title="Click to open file" target="_blank" style="display:block; width: 100%;"&gt;          
        var id = "filename_" + ++index;
        @Html.SpanFor(i =&gt; item.FileName, new { id = id, title = item.FileName, style = "white-space: nowrap;" })          
    &lt;/a&gt;
  &lt;/div&gt;
  }
}

@section Scripts
{
  &lt;script type="text/javascript"&gt;
    function adaptWidth(span) {
      var span = $(span);
      var origfilename = span.text();
      var ext = origfilename.split('.').pop();
      var filename = origfilename.substr(0, origfilename.length - ext.length - 1);
      var text = origfilename;

      while (span.outerWidth() &gt; span.parent().innerWidth()) {
        span.text(text = (filename = filename.substr(0, filename.length - 4) + '...') + ext);
      }
    }

    $(document).ready(function () {
      $('span[id^=filename_]').each(function (i) { adaptWidth(this) });
    });
  &lt;/script&gt;
}


Here are the results before and after running script:

Before:

  

After:



The function runs quite fast for now, but should I be worried from future impact? Any other suggestion or alternatives? Optimization?

I thought about splitting it to 3 spans, 1 for filename, second for ..., and 3rd for the extension, but I don't really know how to make the overflow of the first be hidden under the other two. Besides, if a truncation isn't required, it's gonna look weird.
In general case I would to get text_width and container_width, then calculate new_string_length=container_width/text_width*length, than setup increase or decrease text, depending on result_text_width > container_width  and do the loop like yours.

This is really needed only if strings have a very big size.