1

I have a <div> which is 400px wide and 100px high. I want to put a heading in that which will vary in length, and it will take up two lines in the <div> if it is long enough (i.e the <div> will have a default font size of 50px). I want to have the text start at 50px, and have it to shrink down if the text is too long to fit in to the box on two lines.

How do I go about this? I've been playing around with Javascript for a few hours but I am not able to come up with or find anything. All I can find is how to do this for text on one line.

Sarvap Praharanayuthan
  • 4,212
  • 7
  • 47
  • 72
user2637397
  • 45
  • 1
  • 1
  • 6

1 Answers1

6

You will need some JavaScript to solve this. This is my example markup

<div style="width: 400px; border: 1px solid black;">
    <span style="display: inline-block; font-size: 50px;">This is my text that I want to fit</span>
</div>

I gave the span the display value inline-block so I could measuer its width.

Then the following jquery based script will make it shink until it's just a little bit too small.

$(function() {
    var span = $('span');
    var fontSize = parseInt(span.css('font-size'));

    do {
        fontSize--;
        span.css('font-size', fontSize.toString() + 'px');
    } while (span.width() >= 400);
});

Check out the JSFiddle for demonstration: http://jsfiddle.net/gEjTz/

UweB
  • 4,080
  • 2
  • 16
  • 28