Fit text perfectly inside a div (height and width) without affecting the size of the div

Here’s the same answer, but in Javascript

var autoSizeText;

autoSizeText = function() {
  var el, elements, _i, _len, _results;
  elements = $('.resize');
  console.log(elements);
  if (elements.length < 0) {
    return;
  }
  _results = [];
  for (_i = 0, _len = elements.length; _i < _len; _i++) {
    el = elements[_i];
    _results.push((function(el) {
      var resizeText, _results1;
      resizeText = function() {
        var elNewFontSize;
        elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';
        return $(el).css('font-size', elNewFontSize);
      };
      _results1 = [];
      while (el.scrollHeight > el.offsetHeight) {
        _results1.push(resizeText());
      }
       return _results1;
    })(el));
  }
  return _results;
};

$(document).ready(function() {
  return autoSizeText();
});

By the way…if you ever need to convert coffeescript to javascript, just go to js2coffee.org

I was wanting something similar myself recently:

<div class="container">
    <div class="no-resize">This text won't be resized and will go out of the div.</div>
    <div class="resize">This text will be resized and wont go out of the div.</div>
</div>

And

.no-resize, .resize {
    width: 100px;
    height: 50px;
    border: 1px solid #000;
    color: #000;
    float: left;
    margin-left: 10px;
    font-size: 15px
}

Fiddler at jsfiddle.net/mn4rr/1/.

Leave a Comment