Created
February 22, 2017 10:40
-
-
Save apendua/4d664a30680a5dd85ec0c635dc7074a1 to your computer and use it in GitHub Desktop.
Calculate approximate font size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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