I apologise in advance as I know this question has come up many times before but I just can\'t seem to find the right solution (and believe me I\'ve tried a few!)
Ba
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
Sorry late answer but can saves time of many, I write this code which works perfectly during resize of window.
function fitTextInDiv(){
if($this.find('.text-wrapper').height() > $this.find('.aligned-text').height() ){
while( $this.find('.text-wrapper').height() > $this.find('.aligned-text').height() ) {
$this.find('.aligned-text').css('font-size', (parseFloat($this.find('.aligned-text').css('font-size')) + 0.1) + "px" );
}
}
else if($this.find('.text-wrapper').height() < $this.find('.aligned-text').height() ){
while( $this.find('.text-wrapper').height() < $this.find('.aligned-text').height() ) {
$this.find('.aligned-text').css('font-size', (parseFloat($this.find('.aligned-text').css('font-size')) - 0.1) + "px" );
}
}
}
Where text-wrapper is parent and aligned-text is child div. You must specify height and width of parent element. In resize you can set height and width of parent element by using jquery then call this function.
I write this code because I tried my many plugins but they don't support resizing window.
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 solved this by making a jQuery plugin, it's here: http://jsfiddle.net/c9YNz/2/ (Updated to deal with resizing windows)
The code for the plugin just shrinks the text down to 0.01em size and then grows it to fit, here's the plugin code:
$.fn.resizeText = function () {
var width = $(this).innerWidth();
var height = $(this).innerHeight();
var html = $(this).html();
var newElem = $("<div>", {
html: html,
style: "display: inline-block;overflow:hidden;font-size:0.1em;padding:0;margin:0;border:0;outline:0"
});
$(this).html(newElem);
$.resizeText.increaseSize(10, 0.1, newElem, width, height);
$(window).resize(function () {
if ($.resizeText.interval)
clearTimeout($.resizeText.interval)
$.resizeText.interval = setTimeout(function () {
elem.html(elem.find("div.createdResizeObject").first().html());
elem.resizeText();
}, 300);
});
}
$.resizeText = {
increaseSize: function (increment, start, newElem, width, height) {
var fontSize = start;
while (newElem.outerWidth() <= width && newElem.outerHeight() <= height) {
fontSize += increment;
newElem.css("font-size", fontSize + "em");
}
if (newElem.outerWidth() > width || newElem.outerHeight() > height) {
fontSize -= increment;
newElem.css("font-size", fontSize + "em");
if (increment > 0.1) {
$.resizeText.increaseSize(increment / 10, fontSize, newElem, width, height);
}
}
}
};
Then if you have this html:
<div class="resizeText" style="width:1200px;height:400px;">
Insert text from slipsum here.
</div>
You call it just like this:
$(document).ready(function () {
$(".resizeText").resizeText();
});
It's not the best way to do it, but it's enough for you to be going on with, I would imagine (plus it works).
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.
I recently had a max width div that was receiving text from a text input field and I had to make the text fit in that div, so here is how I solved it (simple JS, no plugin):
function addName(){
let maxWidth = 550;
let defaultFontSize = 50;
let entry = document.getElementById('nameInput').value;
let nameDiv = document.getElementById('name');
let fontSize = nameDiv.style["font-size"];
fontSize = fontSize.replace('px','');
fontSize = parseInt(fontSize);
nameDiv.innerText = entry;
if (nameDiv.clientWidth > maxWidth) {
fontSize = fontSize - 2.5;
nameDiv.style["font-size"] = `${fontSize}px`;
} else if (nameDiv.clientWidth < maxWidth && fontSize < defaultFontSize ) {
fontSize = fontSize + 2.5;
nameDiv.style["font-size"] = `${fontSize}px`;
}
}
#name {
height: 70px;
line-height: 70px;
text-align: center;
overflow: hidden;
width: auto;
display: table; /*THAT DOES THE MAGIC*/
margin: auto;
border: 1px solid black
/* THE BORDER IS FOR TEST PURPOSES TO SEE WHAT'S HAPPENING WITH THE DIV*/
}
<input type="text" id="nameInput" oninput="addName()">
<div id="name" style="font-size: 50px;"></div>