Skip to content

Instantly share code, notes, and snippets.

@puncoz
Created January 7, 2019 08:57
Show Gist options
  • Save puncoz/4e9e5bc948804a7744b304cd3a688ed3 to your computer and use it in GitHub Desktop.
Save puncoz/4e9e5bc948804a7744b304cd3a688ed3 to your computer and use it in GitHub Desktop.
Responsive Text, calculated font-size with respect to content wrapper.
export const responsiveText = (selector) => {
const rtWrappers = document.querySelectorAll(selector)
rtWrappers.forEach(wrapper => {
const width = wrapper.offsetWidth,
height = wrapper.offsetHeight,
text = wrapper.innerHTML
let textLength = typeof text === "string" ? text.trim().replace(" ", "").length : 0
const bestRatio = height / 1.4
let fontSize = 0
if (textLength > 0) {
fontSize = Math.floor(1.5 * width / textLength)
}
wrapper.style.fontSize = (fontSize > bestRatio ? bestRatio : fontSize) + "px"
wrapper.style.lineHeight = height + "px"
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment