Skip to content

Instantly share code, notes, and snippets.

@garystorey
Created July 21, 2017 16:44
Show Gist options
  • Save garystorey/8acada4205ea2f731c40c082459801cf to your computer and use it in GitHub Desktop.
Save garystorey/8acada4205ea2f731c40c082459801cf to your computer and use it in GitHub Desktop.
function maximizeFontSize(elem, maxWidth, maxHeight, opt_dontChangeFontSize) {
var canBeBigger,
display = elem.style.display,
fontSize = elem.style.fontSize,
font = elem.style.font,
computedFont = window.getComputedStyle(elem, null).getPropertyValue('font'),
doc = elem.ownerDocument,
parentNode = elem.parentNode,
tempParent = doc.createElement('div'),
nextSibling = elem.nextSibling,
newFontSize = 0.5,
diff = 0.5;
elem.style.display = 'inline-block';
elem.style.font = computedFont;
tempParent.style.display = 'block';
tempParent.style.width = maxWidth;
tempParent.style.height = maxHeight;
tempParent.style.overflow = 'hidden';
doc.body.appendChild(tempParent);
tempParent.appendChild(elem);
do {
newFontSize += diff;
elem.style.fontSize = newFontSize + 'px';
if (canBeBigger = (elem.clientWidth <= maxWidth && elem.clientHeight <= maxHeight)) {
diff *= 2;
}
else {
newFontSize -= diff;
diff /= 2;
}
} while((!canBeBigger && newFontSize > 0.5) || diff >= 1);
if (opt_dontChangeFontSize || !canBeBigger) {
elem.style.fontSize = fontSize;
}
doc.body.removeChild(tempParent);
parentNode.insertBefore(elem, nextSibling);
elem.style.display = display;
if (font) {
elem.style.font = (opt_dontChangeFontSize || !canBeBigger) ? font : font.replace(/\b(\d+(\.\d+)?|\.\d+)[A-Za-z]+\b/, newFontSize + 'px');
}
else {
delete elem.style.font;
}
return canBeBigger ? newFontSize : undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment