Skip to content

Instantly share code, notes, and snippets.

@chuyeow
Created October 22, 2010 08:06
Show Gist options
  • Save chuyeow/640142 to your computer and use it in GitHub Desktop.
Save chuyeow/640142 to your computer and use it in GitHub Desktop.
Reduce font-size of text in $target to fit into a single line if necessary.
var $target = $('#selector');
var target_width = $target.parent(':first').width();
var $span = $('<span></span>');
$span.css({
'display': 'inline',
'visibility': 'hidden',
'font-size': parseInt($target.css('font-size'), 10),
'font-weight': $target.css('font-weight'),
'white-space': 'nowrap'
});
$span.text($target.text());
$span.appendTo('body');
while($span.width() > target_width && parseInt($span.css('font-size'), 10) >= 5) {
$span.css('font-size', (parseInt($span.css('font-size'), 10) - 1) + 'px');
}
$target.css('font-size', $span.css('font-size'));
$span.remove();
@chuyeow
Copy link
Author

chuyeow commented Oct 22, 2010

Not 100% full-proof depending on block-level CSS, and requires a parent container around $target that we want to fit the text in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment