HTML / CSS - adjust font-size to fill parent height and width

前端 未结 5 1029
梦毁少年i
梦毁少年i 2020-12-03 11:04

I have a

element that resizes as the browser window resizes.

Inside the

I have a paragraph of text:



        
相关标签:
5条回答
  • 2020-12-03 11:41

    There's a jquery plugin for this: http://fittextjs.com/

    0 讨论(0)
  • 2020-12-03 11:44

    HTML

    <div id="change" style="margin:10%;"> 
        <p>Paragraph of text. Paragraph of text. Paragraph of text.</p> 
    </div> 
    

    CSS

    #change { 
        width: 80%; 
        height: 80%; 
        border: 1px solid black; 
        overflow: hidden; 
        font-size: 1em; 
    } 
    

    JAVASCRIPT

    $(function() { 
        while( $('#change div').height() > $('#change').height() ) { 
            $('#change div').css('font-size', (parseInt($('#change div').css('font-size')) - 1) + "px" ); 
        } 
    }); 
    
    0 讨论(0)
  • 2020-12-03 11:50

    Check out the vw properties in css

    http://www.w3schools.com/cssref/css_units.asp

    0 讨论(0)
  • 2020-12-03 11:54

    fittext.js did not work correctly for me (plugin for jQuery, as well as derived jquery-free version), nor with using of compressor attribute, so I found another solution:

    http://www.dhtmlgoodies.com/?whichScript=text_fit_in_box (someone's another work)

    which works perfectly for me - longer texts as well as shorter texts.

    It just do not react to resize of window (it works just once on loading of page), so I have written this short code to run it automatically after each window resize (it works for me):

    <script>
          function calculate_font_sizes()
          {
            fitTextInBox('login-h1');
            fitTextInBox('subtittle');
          }
          calculate_font_sizes();
          window.addEventListener('resize', calculate_font_sizes);
    
    </script>
    

    I hope it can help to someone.

    0 讨论(0)
  • 2020-12-03 11:55

    What you need is called vw. Example CSS: font-size: 80vw;. vw means viewerport width, and 80vw = 80% of the device screen width

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