Skip to content

Instantly share code, notes, and snippets.

@apendua
Created February 22, 2017 10:40
Show Gist options
  • Save apendua/4d664a30680a5dd85ec0c635dc7074a1 to your computer and use it in GitHub Desktop.
Save apendua/4d664a30680a5dd85ec0c635dc7074a1 to your computer and use it in GitHub Desktop.
Calculate approximate font size
// Based on:
// http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript
export function fontSize (el = document.body) {
const test = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const div = document.createElement('div');
div.style.position = 'absolute';
div.style.visiblity = 'hidden';
div.style.height = 'auto';
div.style.width = 'auto';
div.style.whiteSpace = 'nowrap';
div.textContent = test;
el.appendChild(div);
const result = (div.clientWidth + 1) / test.length;
el.removeChild(div);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment