Skip to content

Instantly share code, notes, and snippets.

@jobwat
Created June 7, 2011 00:13
Show Gist options
  • Save jobwat/1011409 to your computer and use it in GitHub Desktop.
Save jobwat/1011409 to your computer and use it in GitHub Desktop.
Dynamic resize element text font-size to fit parent element width
Helpers.updateResizeInput = function(el, text){
if(el[0].localName == "input"){ // inputs are a pain (width auto is wrong & innerHTML <> value)
if(text==undefined) text = el[0].value;
el.parent().prepend('<span id="test" />');
var theSpan = $('span#test', el.parent());
theSpan.value = text;
Helpers.updateResizeInput(theSpan, text);
el.css('font-size', theSpan.css('font-size'));
el.css('margin-top', theSpan.css('margin-top'));
el[0].value = text;
theSpan.remove();
}
else{
if(text==undefined) text = el.html();
else el.html(text);
var parentWidth = el.parent().width();
var parentHeight = el.parent().height();
var fontSize = 24; // max, biggest value
el.css('width', 'auto');
el.css('font-size', fontSize+'px');
el.css('margin-top', '6px');
while(el.width() > parentWidth){
fontSize--;
el.css('font-size', fontSize+'px');
el.css('margin-top', (parentHeight-fontSize)/2+'px');
}
el.css('width', parentWidth+'px');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment