22

I have a <div> element that resizes as the browser window resizes.

Inside the <div> I have a paragraph of text:

<div style="width:80%; height:80%; margin:10%;">
    <p>Paragraph of text. Paragraph of text. Paragraph of text.</p>
</div>

I want the text to change font-size as I resize the <div>, so that the text will occuypy 100% of the available space.

How can I achieve this effect?
Would it be with a percentage font-size?
Would I have to use Javascript?

Thanks in advance!

Web_Designer
  • 72,308
  • 93
  • 206
  • 262

4 Answers4

6

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

Bas
  • 103
  • 3
0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

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" ); 
    } 
}); 
Jawad
  • 8,352
  • 10
  • 40
  • 45
  • taken from - http://stackoverflow.com/questions/6112660/how-to-resize-automatically-a-font-size-inside-a-div – Jawad Oct 19 '11 at 18:41
-2

Check out the vw properties in css

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

Nick
  • 3,217
  • 5
  • 30
  • 42
  • 1
    Vw is for width. The user asked for width and height. And his example is not for body. So, your answer is unuseful. – Andrei Dec 26 '20 at 08:36
  • I believe as the width increases the height increases as well. – Nick Jan 10 '21 at 17:04