Text-size auto resizing on div width

后端 未结 1 1436
一个人的身影
一个人的身影 2020-12-22 14:51

I struggle with one problem. I have a div with a specific width and height (227px x 27px). Inside this div comes First and Last name, as a variable. Sometimes this name is s

相关标签:
1条回答
  • 2020-12-22 15:27

    Run this function on page load to resize the text if necessary. The important thing in the css is white-space: nowrap which stops the text from wrapping onto a second line.
    Don't forget to give the test span "d" the same font family, style and weight as the real text.

    function fittext()
    {
        var maxW = 227, maxH = 27, maxSize = 20;
        var c = document.getElementsByClassName("fitin");
        var d = document.createElement("span");
        d.style.fontSize = maxSize + "px";
    
        for (var i = 0; i < c.length; i++)
        {
            d.innerHTML = c[i].innerHTML;
            document.body.appendChild(d);
            var w = d.offsetWidth;
            var h = d.offsetHeight;
            document.body.removeChild(d);
            var x = w > maxW ? maxW / w : 1;
            var y = h > maxH ? maxH / h : 1;
            var r = Math.min(x, y) * maxSize;
            c[i].style.fontSize = r + "px";
        }
    }
    
    fittext();
    DIV
    {
        width: 227px;
        height: 27px;
        overflow: hidden;
        margin-bottom: 9px;
        background-color: silver;
    }
    
    P
    {
        margin: 0px;
        color: black;
        font-size: 20px;
        text-align: center;
        white-space: nowrap;
    }
    <DIV>
        <P>
             <SPAN CLASS="fitin">Short Guy</SPAN>
        </P>
    </DIV>
    <DIV>
        <P>
             <SPAN CLASS="fitin">Just A Random Regular Person</SPAN>
        </P>
    </DIV>
    <DIV>
        <P>
             <SPAN CLASS="fitin">A Really Very Extraordinarily Long And Tall Woman</SPAN>
        </P>
    </DIV>

    0 讨论(0)
提交回复
热议问题