Skip to content

Instantly share code, notes, and snippets.

@GeoffCox
Created March 9, 2015 22:30
Show Gist options
  • Save GeoffCox/3a60afca4c16849f02a5 to your computer and use it in GitHub Desktop.
Save GeoffCox/3a60afca4c16849f02a5 to your computer and use it in GitHub Desktop.
Scale font-size until text fits within element
function scaleFontToFit(element) {
if (element) {
// for an element
var $element = $(element);
if ($element.css("overflow") == "hidden") {
var elementHeight = $element.height();
var fontSize = parseInt($element.css("font-size"), 10);
var $fullElement = $(element).clone().css('overflow', 'visible').height('auto');
$element.after($fullElement);
if ($fullElement.height() > elementHeight) {
while ($fullElement.height() > elementHeight) {
fontSize -= 1;
$fullElement.css("font-size", fontSize);
}
$element.css("font-size", fontSize)
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment