Context: I have an HTML element that must display one-line of text (strictly one-line) and auto-size the font-size to fit within the HTML element (shrink the font when the page is smaller and get bigger as page increases).
I have successfully added a CSS style and javascript function that achieves the text auto-sizing (which is awesome!) BUT…
This only seems to work when the “iFrame” option is checked, but when this is checked, I no longer have the option to fit the HTML container to the content’s height.
Here are some examples that help demonstrate where I’m at:
Note the green outline is the border of the HTML element to help show the height
-
Below: The code with iFrame checked (auto-sized text works, html height does not fit content):
-
Below: The code with iFrame UNchecked (auto-sized text does not work, html height DOES fit content):
So basically, I want to auto-size the font to fit the width of the html element which will change with the page size, as well as fit the height of the html element to the height of the text.
The code I am using in my HTML element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.one-line-text {
font-family: 'Albert Sans';
font-weight: 600;
Color: #ffffff;
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: clip;
display: block;
width: 100%;
line-height: 1.1; /* Ensure the height matches the font size */
}
</style>
</head>
<body>
<div class="one-line-text" id="resizeText">Marcus Pettersson</div>
<script>
function fitTextToContainer(element, maxFontSize) {
let containerWidth = element.clientWidth;
let fontSize = maxFontSize;
element.style.fontSize = fontSize + 'px';
// Decrease font size until text fits within container
while (element.scrollWidth > containerWidth && fontSize > 0) {
fontSize -= 1;
element.style.fontSize = fontSize + 'px';
}
// Increase font size until text fills container width (if possible)
while (element.scrollWidth < containerWidth && fontSize < maxFontSize) {
fontSize += 1;
element.style.fontSize = fontSize + 'px';
if (element.scrollWidth > containerWidth) {
fontSize -= 1;
element.style.fontSize = fontSize + 'px';
break;
}
}
// Adjust container height to fit the text
let lineHeight = window.getComputedStyle(element).lineHeight;
element.style.height = lineHeight;
}
document.addEventListener('DOMContentLoaded', function() {
const textElement = document.getElementById('resizeText');
fitTextToContainer(textElement, 88); // Set the maxFontSize to 88px
window.addEventListener('resize', () => {
fitTextToContainer(textElement, 88); // Reapply on resize
});
});
</script>
</body>
</html>
Any help is appreciated!