March 24, 2012
Scale text string to given width
Question by santa
Is it possible to scale a text string’s size with CSS or jQuery if the width of the allocated space is known? I need it to increase font size without wrapping the string.
Let’s say I have something like this:
<div style="width:600px">My text string here.</div>
I suppose I could measure the width by wrapping the string in span
JS:
var strWidth = $("#myStr").width(),
strFontS = 20;
if (strWidth < 600) {
// maybe increase font-size
$("#myStr").css("font-size", strFontS + 1 + "px");
}
HTML:
<div id="myDiv" style="width:600px"><span id="myStr">My text string here.</span></div>
Answer by Starx
Here is a plugin I made, which you can use to resize the text
$.fn.resizeText = function(){
var size = parseInt($(this).css("fontSize"));
var html = $(this).html();
var textLength = html.length;
var span = '<span>' + html + '</span>';
$(this).html(span);
var width = $(this).find('span:first').width();
$(this).html(html);
var newSize = $(this).width()/width*size;
$(this).css("fontSize", newSize);
return width;
};
Usage:
$("div").resizeText();
Check out the demo.