philchanet
8/3/2016 - 10:35 AM

Adapt multiline text to container size

Adapt multiline text to container size

<html>
<head>
<style type="text/css">
.dynamicDiv
{
    background: #CCCCCC;
    width: 100vw;
    max-height: 300px;
    font-size: 300px;
    overflow: hidden;
}
</style>

<script type="text/javascript">
    function shrink()
    {
        var textDivs = document.getElementsByClassName("dynamicDiv");
        var textDivsLength = textDivs.length;

        // Loop through all of the dynamic divs on the page
        for(var i=0; i<textDivsLength; i++) {

            var textDiv = textDivs[i];

            // Loop through all of the dynamic spans within the div
            var textSpan = textDiv.getElementsByClassName("dynamicSpan")[0];

            // Use the same looping logic as before
            textSpan.style.fontSize = 300;

            while(textSpan.offsetHeight > textDiv.offsetHeight)
            {
                textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
            }

        }

    }
</script>

</head>
<body onload="shrink()" onresize="shrink()">
    <div class="dynamicDiv"><h1><span class="dynamicSpan">BIG FONT</span></h1></div>
    <br>
    <div class="dynamicDiv"><h2><span class="dynamicSpan">THE BIG FONT</span></h2></div>
    <br>
    <div class="dynamicDiv"><h3><span class="dynamicSpan">ANOTHER DYNAMIC FONT</span></h3></div>
    <br>
    <div class="dynamicDiv"><h4><span class="dynamicSpan">THE SUPER NICE FONT WITH A VERY BEAUTIFUL LONG TEXT</span></h4></div>
</body>
</html>