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

前端 未结 9 1805
盖世英雄少女心
盖世英雄少女心 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:02

    Here's a slightly modified version of the given answers.

    Requirements :

    1. The class containing text has the "resize" class.
    2. it contains height and width (%, px, whatever...)

    What changes in this version ?

    1. I added resizing ( by binding the event resize to the function) autoSizeText. This is far from ideal, but if we don't resize a lot, it should be ok.
    2. In previous versions, text is only getting smaller. Now it tries to find the biggest font without going outside the div.

    Note:

    I don't claim the code is production ready. But if you find something you can enhance, please share it with the community.

    var autoSizeText = function () {
        var el, elements, _i, _len;
        elements = $('.resize');
        if (elements.length < 0) {
            return;
        }
        for (_i = 0, _len = elements.length; _i < _len; _i++) {
            el = elements[_i];
            dichoFit = function (el) {
    
                diminishText = function () {
                    var elNewFontSize;
                    elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';
    
                    return $(el).css('font-size', elNewFontSize);
                };
                augmentText = function () {
                    var elNewFontSize;
                    elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) + 1) + 'px';
    
                    return $(el).css('font-size', elNewFontSize);
                };
    
    
                diminishText();
                while (el.scrollHeight < el.offsetHeight) {
                    augmentText();
                }
                augmentText();
                while (el.scrollHeight > el.offsetHeight) {
                    diminishText();
                }
    
            }
            dichoFit(el);
        }
    };
    
    $(document).ready(function () {
        autoSizeText();
        $(window).resize(function resizeText(){
            autoSizeText()
        })
    });
    .sizable{
     width: 50vw;
     height: 50vh;
     border: 2px solid darkred;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
      <div class='sizable resize'>
      I am a sizable div and I have explicit width and height.
    </div>

    0 讨论(0)
  • 2020-12-02 18:04

    Here's my version. This is build with ES6 on a React project.

    export function autoSizeText(container, attempts=30) {
      let setChildrenToInheritFontSize = ( el ) => {
        el.style.fontSize = 'inherit';
        _.each( el.children, (child) => {
          setChildrenToInheritFontSize( child );
        });
      };
    
    
      let resizeText = (el) => {
        attempts--;
        let elNewFontSize;
        if( el.style.fontSize === "" ||  el.style.fontSize === "inherit" ||  el.style.fontSize === "NaN" ){
          elNewFontSize = '32px'; // largest font to start with
        } else {
          elNewFontSize = (parseInt(el.style.fontSize.slice(0, -2)) - 1) + 'px';
        }
        el.style.fontSize = elNewFontSize;
    
        // this function can crash the app, so we need to limit it
        if( attempts <= 0 ) {
          return;
        }
    
        if ( (el.scrollWidth > el.offsetWidth) || (el.scrollHeight > el.offsetHeight)) {
          resizeText(el);
        }
      };
      setChildrenToInheritFontSize( container );
      resizeText(container);
    }
    
    0 讨论(0)
  • 2020-12-02 18:08

    I got the same problem and the solution is basically use javascript to control font-size. Check this example on codepen:

    https://codepen.io/ThePostModernPlatonic/pen/BZKzVR
    

    try to resize it

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Documento sem título</title>
    <style>
    </style>
    </head>
    <body>
    <div style="height:100vh;background-color: tomato;" id="wrap">        
      <h1 class="quote" id="quotee" style="padding-top: 56px">Because too much "light" doesn't <em>illuminate</em> our paths and warm us, it only blinds and burns us.</h1>
    </div>
    </body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script>
      var multiplexador = 3;
      initial_div_height = document.getElementById ("wrap").scrollHeight;
      setInterval(function(){ 
        var div = document.getElementById ("wrap");
        var frase = document.getElementById ("quotee");
        var message = "WIDTH div " + div.scrollWidth + "px. "+ frase.scrollWidth+"px. frase \n";
        message += "HEIGHT div " + initial_div_height + "px. "+ frase.scrollHeight+"px. frase \n";           
        if (frase.scrollHeight < initial_div_height - 30){
          multiplexador += 1;
          $("#quotee").css("font-size", multiplexador); 
        }
        console.log(message);          
      }, 10);
    </script>
    </html>
    
    0 讨论(0)
提交回复
热议问题