3

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>
santa
  • 12,234
  • 49
  • 155
  • 255

2 Answers2

2

You need measure the width of text width given font and size. A jquery function for calculate textMetric. After than u can find a rate. And enlarge or recude the font size to fit the give element.

And here my simple example how it works: http://jsfiddle.net/PKkLL/7/

Community
  • 1
  • 1
safarov
  • 7,793
  • 2
  • 36
  • 52
1

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.

Starx
  • 77,474
  • 47
  • 185
  • 261