Fit text perfectly inside a div (height and width) without affecting the size of the div

前端 未结 9 1851
盖世英雄少女心
盖世英雄少女心 2020-12-02 17:07

I apologise in advance as I know this question has come up many times before but I just can\'t seem to find the right solution (and believe me I\'ve tried a few!)

Ba

9条回答
  •  不知归路
    2020-12-02 18:01

    I recently had a max width div that was receiving text from a text input field and I had to make the text fit in that div, so here is how I solved it (simple JS, no plugin):

    function addName(){
        let maxWidth = 550;
        let defaultFontSize = 50;
        let entry = document.getElementById('nameInput').value;
        let nameDiv = document.getElementById('name');
        let fontSize = nameDiv.style["font-size"];
        fontSize = fontSize.replace('px','');
        fontSize = parseInt(fontSize);
        nameDiv.innerText = entry;
        if (nameDiv.clientWidth > maxWidth) {
            fontSize = fontSize - 2.5;
            nameDiv.style["font-size"] = `${fontSize}px`;
        } else if (nameDiv.clientWidth < maxWidth && fontSize < defaultFontSize ) {
            fontSize = fontSize + 2.5;
            nameDiv.style["font-size"] = `${fontSize}px`;
        }
    }
    #name {
        height: 70px;
        line-height: 70px;
        text-align: center;
        overflow: hidden;
        width: auto;
        display: table; /*THAT DOES THE MAGIC*/
        margin: auto;
        border: 1px solid black
    /* THE BORDER IS FOR TEST PURPOSES TO SEE WHAT'S HAPPENING WITH THE DIV*/
    }
    
    

提交回复
热议问题