Created
February 1, 2012 00:57
-
-
Save jesstelford/1714284 to your computer and use it in GitHub Desktop.
jQuery Plugin to resize text to fit container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
maxHeight = parent.height() is never used
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
HTML
JavaScript
and restricting 20 <= font-size <= 50:
See test case on jsFiddle