This method may not yield pixel-perfect results, but it provides an approximate outcome.
By enclosing the text within a <span>
tag, you can determine the initial text width and font size, which are essential for calculating the final font size based on the container's width.
window.addEventListener('resize', adjustFontSize);
var textElement = document.querySelector('span'),
textParent = textElement.parentNode,
fontSize = parseFloat(window.getComputedStyle(textElement, null).getPropertyValue('font-size')),
textWidth = textElement.clientWidth,
remainingSpace;
function adjustFontSize() {
remainingSpace = textParent.clientWidth;
textElement.style.fontSize = (remainingSpace * fontSize)/textWidth + "px";
}
adjustFontSize();
html {
background-color: #fff;
}
body {
background-color: #f3f3f3;
display: flex;
text-align: center;
justify-content: center;
margin: 0 8%;
}
<body>
<span>hello</span>
</body>