Skip to content

Instantly share code, notes, and snippets.

@jackreichert
Created September 13, 2011 21:34
Show Gist options
  • Save jackreichert/1215233 to your computer and use it in GitHub Desktop.
Save jackreichert/1215233 to your computer and use it in GitHub Desktop.
jQuery function to resize fonts to fit a containing element.
$.fn.fontBefitting = function() { // This resizes fonts to make them fit in an element
return this.each(function() {
var fontSize = parseFloat($(this).css('fontSize'));
this.style.overflowY = 'scroll';
// This is if the font too big to fit an enclosing element
while (this.clientHeight < this.scrollHeight && fontSize > 1) {
fontSize *= 0.99;
$(this).css('fontSize',fontSize + 'px');
}
// This is if the font is too small
while ((this.clientHeight > this.scrollHeight || this.clientHeight == this.scrollHeight) && fontSize < 100) {
fontSize *= 1.01;
$(this).css('fontSize',fontSize + 'px');
}
// Brings the font-size back under the limit.
fontSize /= 1.01;
$(this).css('fontSize',fontSize + 'px');
this.style.overflowY = 'visible';
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment