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/.
I don't have enough reputation to comment on the accepted answer so I made an answer. If height
has a css3 transition on it the autoSizeText()
and $.resizeText
answers above have issues. I made a short jquery plugin to fix this.
$.fn.resizeText = function (options) {
var settings = $.extend({ maxfont: 40, minfont: 4 }, options);
var style = $('<style>').html('.nodelays ' +
'{ ' +
'-moz-transition: none !important; ' +
'-webkit-transition: none !important;' +
'-o-transition: none !important; ' +
'transition: none !important;' +
'}');
function shrink(el, fontsize, minfontsize)
{
if (fontsize < minfontsize) return;
el.style.fontSize = fontsize + 'px';
if (el.scrollHeight > el.offsetHeight) shrink(el, fontsize - 1, minfontsize);
}
$('head').append(style);
$(this).each(function(index, el)
{
var element = $(el);
element.addClass('nodelays');
shrink(el, settings.maxfont, settings.minfont);
element.removeClass('nodelays');
});
style.remove();
}
To use this plugin you only need to call
$(selector).resizeText();
I hope this saves someone else some time troubleshooting. I wasted a good 20 minutes scratching my head wondering why the code above was causing an infinite loop on my page.