Skip to content

Instantly share code, notes, and snippets.

@meirish
Created May 31, 2011 03:43
Show Gist options
  • Save meirish/999827 to your computer and use it in GitHub Desktop.
Save meirish/999827 to your computer and use it in GitHub Desktop.
var setTextMeasure = function (contentElement, targetMeasure, maxSize, minSize) {
if (!contentElement) contentElement = $(document.createElement('p'));
if (!targetMeasure) targetMeasure = 66;
if (!maxSize) maxSize = 16;
if (!minSize) minSize = 9;
var body = $('body');
var sizer = contentElement.clone();
sizer.css({'margin': 0, 'padding': 0, 'color': 'transparent', 'backgroundColor': 'transparent', 'position': 'absolute'});
var letters = 'aaaaaaaabbcccddddeeeeeeeeeeeeeffgghhhhhhiiiiiiijkllllmmnnnnnnnooooooooppqrrrrrrsssssstttttttttuuuvwxyyz';
sizer.text(letters);
body.append(sizer);
var characterWidth = sizer.width() / letters.length;
sizer.remove();
var contentWidth = contentElement.width();
var measuredFontSize = parseFloat( body.css('font-size').replace('px', '') );
var actualMeasure = contentWidth / characterWidth;
var newMeasure = measuredFontSize * actualMeasure / targetMeasure;
if (newMeasure > maxSize) newMeasure = maxSize;
if (newMeasure < minSize) newMeasure = minSize;
body.css('font-size', newMeasure + "px");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment