Skip to content

Instantly share code, notes, and snippets.

@juliankrispel
Created October 24, 2012 10:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save juliankrispel/3945316 to your computer and use it in GitHub Desktop.
Save juliankrispel/3945316 to your computer and use it in GitHub Desktop.
jQuery Plugin to resize text to fit container
(function($) {
$.fn.textfill = function(maxFontSize) {
maxFontSize = parseInt(maxFontSize, 10);
return this.each(function(){
var ourText = $("span", this);
function resizefont(){
var parent = ourText.parent(),
maxHeight = parent.height(),
maxWidth = parent.width(),
fontSize = parseInt(ourText.css("fontSize"), 10),
multiplier = maxWidth/ourText.width(),
newSize = (fontSize*(multiplier));
ourText.css("fontSize", maxFontSize > 0 && newSize > maxFontSize ? maxFontSize : newSize );
}
$(window).resize(function(){
resizefont();
});
resizefont();
});
};
})(jQuery);
@ADParris
Copy link

ADParris commented Dec 2, 2012

This is nearly perfect. Any idea how to keep the a title in two words during the auto re-sizing? What I mean is... Say my title is "The End". At first it re-sizes to the width of the container perfectly but then when you re-size the browser it becomes "The" on top of "End"(word wrap activates). I'd like the re-size to remain "The End".

@ADParris
Copy link

ADParris commented Dec 2, 2012

CSS did the trick, sorry I would have deleted my comment but they don't appear to allow that here.

white-space: nowrap;

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