views:

268

answers:

2

Hello there :)

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.

Thank you for your time.

Kind regards
Marius

+1  A: 

See the TextFill jQuery plugin that was created as part of the answer to http://stackoverflow.com/questions/687998/auto-size-dynamic-text-to-fill-fixed-size-container

Pär Wieslander
+2  A: 

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