Skip to content

Instantly share code, notes, and snippets.

@jesstelford
Created February 1, 2012 00:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jesstelford/1714284 to your computer and use it in GitHub Desktop.
Save jesstelford/1714284 to your computer and use it in GitHub Desktop.
jQuery Plugin to resize text to fit container
(function($) {
$.fn.textfill = function(maxFontSizePx, minFontSizePx, element) {
maxFontSizePx = parseInt(maxFontSizePx, 10);
minFontSizePx = parseInt(minFontSizePx, 10);
if (maxFontSizePx > 0 && minFontSizePx > maxFontSizePx) {
minFontSizePx = maxFontSizePx;
}
element = typeof(element) == "string" ? element : "span";
return this.each(function(){
var ourText = $(element, this),
parent = ourText.parent(),
maxHeight = parent.height(),
maxWidth = parent.width(),
fontSize = parseInt(ourText.css("fontSize"), 10),
multiplier = maxWidth/ourText.width(),
newSize = (fontSize*(multiplier-0.1));
if (maxFontSizePx > 0 && newSize > maxFontSizePx) {
newSize = maxFontSizePx;
} else if(minFontSizePx > 0 && newSize < minFontSizePx) {
newSize = minFontSizePx;
}
ourText.css("fontSize",newSize);
});
};
})(jQuery);
@jesstelford
Copy link
Author

HTML

<div><span>Text to fit</span></div>

JavaScript

$("div").textfill();

and restricting 20 <= font-size <= 50:

$("div").textfill(50, 20);

See test case on jsFiddle

@howdu
Copy link

howdu commented Sep 5, 2012

maxHeight = parent.height() is never used

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment