scale text to fit on window resize
by J. Jones
HTML
<div class="scale-text styles">
This is a test of scaling text to fit the container. Lorem Ipsum Dolor Sit Amet.
</div>
<div id="font-metrics"></div>
CSS
#scale-text {
white-space: no-wrap;
}
.styles {
width: 100%;
}
#font-metrics {
position: absolute;
z-index: -1;
visibility: hidden;
left: 0;
top: 0;
white-space: no-wrap;
width: auto !important;
}
JavaScript
var fontMetrics = document.getElementById('font-metrics');
var scaleTexts = $('.scale-text');
$(window).on('resize', updateFontSize);
updateFontSize();
function updateFontSize()
{
scaleTexts.each(function()
{
var $scaleText = $$(this);
fontMetrics.innerHTML = this.innerHTML;
fontMetrics.style.fontFamily = $scaleText.css('font-family');
fontMetrics.style.fontWeight = $scaleText.css('font-weight');
fontMetrics.style.fontStyle = $scaleText.css('font-style');
fontMetrics.style.textTransform = $scaleText.css('text-transform');
var fontSize = 50; // max font-size to test
fontMetrics.style.fontSize = fontSize + 'px';
while ($$(fontMetrics).width() > $scaleText.width() && fontSize >= 0)
{
fontSize -= 1;
fontMetrics.style.fontSize = fontSize + 'px';
}
this.style.fontSize = fontSize + 'px';
});
}
function $$(object)
{
if (!object.jquery)
object.jquery = $(object);
return object.jquery;
}