dynamically changing the size of font size based on text length using css and html

前端 未结 8 1235

I need to display user entered text into a fixed size div. What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible.<

相关标签:
8条回答
  • 2020-12-08 05:00

    If by text length you mean character count, there is this article which points to a short jquery snippet Change Font Size dynamically based on Character count

    http://jsfiddle.net/jfbrLjt2/

     $('.text').each(function(){
     var el= $(this);
       var textLength = el.html().length;
        if (textLength > 20) {
            el.css('font-size', '0.8em');
        }
    });
    
    0 讨论(0)
  • 2020-12-08 05:09

    Based on the logic of the top answer here, I created a no-jQuery version,

    const input = document.querySelector('input');
    const output = document.querySelector('.output');
    const outputContainer = document.querySelector('.container');
    
    function resize_to_fit() {
      let fontSize = window.getComputedStyle(output).fontSize;
      output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';
      
      if(output.clientHeight >= outputContainer.clientHeight){
        resize_to_fit();
      }
    }
    
    function processInput() { 
      output.innerHTML =this.value;
      output.style.fontSize = '100px'; // Default font size
      resize_to_fit();
    }
    
    input.addEventListener('input', processInput);
    <input type="text" placeholder="Add text input here" style="margin: 10px; width:50%;">
    
    <div id="outer" class="container" 
    style="width:80%; height:100px; border:2px solid red; font-size:20px;">
      
    <div class="output" style="word-break: break-all; word-wrap: break-word;">
    </div>
    
    </div>

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