Hello, I'm Aaron Harun, a New York based
Traveler, Developer and Web Consultant.
You're about to have an "AaHa!" moment.

Dynamically Resizing Text with jQuery

Dynamically resized text ensures that when necessary, text can fit to a pixel-perfect width in any browser and any operating system. While fonts are similar enough across most browsers and OS, in headlines or other locations where overflow text would break layout, occasionally, one browser will have issues where otheres don’t. In this case, we can ensure that all browsers work at once with a little jQuery.

dynamically-resized-text

See the Demo

The demo is made of three snippets:

The HTML:

<div id="demo">
<p>All of these lines will have different font sizes.</p>
<p>This is because we have set the white-space property of the p tags to "pre."</p>
<p>This means that these lines won't wrap, and because they won't ever wrap, when the page loads,</p>
<p>The JS will attempt to fit the spans inside the p tags. Of course, this could be done with p tags inside of divs.</p>
</div>

The CSS:

#demo p{
white-space:pre;
}
#demo {
width:600px;
}

And the JS magic that fits a span into every p tag and then scales the font by percents.

<script type="text/javascript">
jQuery("#demo p")
    .contents()
    .filter(
        function(){
            return this.nodeType != 1; 
        })
    .wrap("<span/>").parent().each(
	function(){
		var size = 100;
		while(jQuery(this).parent().width() < jQuery(this).width() && size > 5){
			size -= 1;
			jQuery(this).css({'font-size' : size+'%'});
		}
	}
);

</script>

Tagged with: ,
Posted in Demo, Hacks, JavaScript

Leave a Reply

Standard Rules Apply: Use <code> tags for code snippets. Keep it relevant. Other than that, be your awesome self.

*(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

The Archive (Sounds ominous, right?)
Categories (Oh! Look at them all)
`