Scale text string to given width
Is it possible to scale the size of a text string using CSS or jQuery if the width of the allocated space is known? I need this to increase the font size without line wrapping.
Let's say I have something like this:
<div style="width:600px">My text string here.</div>
I guess I can measure the width by wrapping the string in a 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>
+3
source to share
2 answers
You need to measure the width of the text width given by font and size. Jquery function to calculate textMetric . Once you can find a course. And increase or deselect the font size to fit the give element.
And here's my simple example: how it works: http://jsfiddle.net/PKkLL/7/
+2
source to share
Here is a plugin I made that you can use to change the text size
$.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;
};
Using:
$("div").resizeText();
View a demo.
+1
source to share