3

I am writing an application, and in it, I would like to have some h1 elements with variable font size.

I use the full width (1000px) of a div as a limiter, and a script that automatically sets the font of the h1-element so that it fits the width of the div without line break.

This is quite easy to do with php GD, but I thought I wanted to do this client side.

Kara
  • 6,115
  • 16
  • 50
  • 57
Marius
  • 219
  • 1
  • 3
  • 11
  • All I can imagine is that you'd increase the font size until the space consumed by the header element exceeds the size of the box it's in, and then shrink it back. – Pointy Mar 26 '10 at 13:23
  • To be honest, it sounds like a ghastly thing to do. Imagine if your text string was only one character! It would massive! If you still want to look into this, javascript is able to read a innerWidth property of an element. Be warned though, some browser try to speed up code by only actually rendering changes once the code has stopped, so if you kept increasing the font till the width was right, you may not actually see the width changing. – thecoshman Mar 26 '10 at 13:24

2 Answers2

2

See the TextFill jQuery plugin that was created as part of the answer to Auto-size dynamic text to fill fixed size container

Community
  • 1
  • 1
Pär Wieslander
  • 28,374
  • 7
  • 55
  • 54
2

I don't think there is a pre-built function for this. I guess you'll have no choice but to run a loop and resize the element until it fits.

It could work like this:

  • Create a clone of the DIV, with jQuery e.g. element = $('element_id').clone()

  • Set the clone's font-size to 1

  • Build a loop that

    1. Increases font-size by one pixel
    2. Checks whether the desired width has been reached
    3. If it has, breaks the loop

the font-size in the cloned element will then be the closest match for your desired width.

Update: The plugin referenced in @Pär's answer does exactly this.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088