Skip to content

Instantly share code, notes, and snippets.

@setola
Created June 26, 2012 08:51
Show Gist options
  • Save setola/2994490 to your computer and use it in GitHub Desktop.
Save setola/2994490 to your computer and use it in GitHub Desktop.
Font Size to fit container's witdh
jQuery(document).ready(function(){
jQuery('#container1 .auto-size').textAutoSize({
width: 249,
maxSize: 200,
minSize: 5,
//testEl: jQuery('#auto-size-test'),
mode: "ite-binary"
});
jQuery('#container2 .auto-size').textAutoSize({
maxSize: 100,
minSize: 10,
//testEl: jQuery('#auto-size-test2'),
mode: "rec-binary"
});
});
jQuery.fn.textWidth = function(fontSize, testEl){
var toRet = testEl.css({
"font-size": fontSize+'px'
});
var text = jQuery(this).html();
toRet.html(text);
jQuery(this).append(toRet);
var width = toRet.outerWidth(true);
toRet.html('');
return width;
};
jQuery.fn.textAutoSize = function(options){
var testElID = 'test-'+Math.floor((Math.random()*10000)+1);
settings = {
width: 200,
maxSize: 100,
minSize: 10,
testEl: jQuery('<span/>',{"class":"antani"}),
maxIterations: 20,
minGrain: 0.5,
maxGrain: 0.5
};
if(options) jQuery.extend(settings,options);
settings.testEl.attr('id', testElID);
jQuery(this).each(function(){
if(jQuery(this).text().lenght == 0) return;
var currentSize;
var currentWidth;
var maxIterations = settings.maxIterations;
var boundMax = settings.maxSize;
var boundMin = settings.minSize;
do {
maxIterations--;
currentSize = ( boundMax - boundMin ) / 2 + boundMin;
currentWidth = jQuery(this).textWidth(currentSize, settings.testEl);
if(currentWidth > settings.width){
boundMax = currentSize - settings.maxGrain;
} else {
boundMin = currentSize + settings.minGrain;
}
} while( boundMin < boundMax && maxIterations > 0);
jQuery(this).css('font-size',currentSize+'px');
/*console.log(jQuery(this).text());
console.log(currentSize);
console.log(20-maxIterations);
console.log('-------------------');*/
});
jQuery('#'+testElID).remove();
};
.project-.text-container {
margin: 10px;
width: 250px;
border: 1px solid #c00;
line-height: 1;
font-family: Century Gothic, CenturyGothic, AppleGothic, sans-serif;
text-align: center;
/*white-space: nowrap;*/
}
.auto-size {
margin: 0;
padding: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment