I apologise in advance as I know this question has come up many times before but I just can\'t seem to find the right solution (and believe me I\'ve tried a few!)
Ba
Here's my version. This is build with ES6 on a React project.
export function autoSizeText(container, attempts=30) {
let setChildrenToInheritFontSize = ( el ) => {
el.style.fontSize = 'inherit';
_.each( el.children, (child) => {
setChildrenToInheritFontSize( child );
});
};
let resizeText = (el) => {
attempts--;
let elNewFontSize;
if( el.style.fontSize === "" || el.style.fontSize === "inherit" || el.style.fontSize === "NaN" ){
elNewFontSize = '32px'; // largest font to start with
} else {
elNewFontSize = (parseInt(el.style.fontSize.slice(0, -2)) - 1) + 'px';
}
el.style.fontSize = elNewFontSize;
// this function can crash the app, so we need to limit it
if( attempts <= 0 ) {
return;
}
if ( (el.scrollWidth > el.offsetWidth) || (el.scrollHeight > el.offsetHeight)) {
resizeText(el);
}
};
setChildrenToInheritFontSize( container );
resizeText(container);
}