Skip to content

Instantly share code, notes, and snippets.

@ronaldroe
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronaldroe/7e1de748dc29420d1c63 to your computer and use it in GitHub Desktop.
Save ronaldroe/7e1de748dc29420d1c63 to your computer and use it in GitHub Desktop.
The Poor Man's FitText
/* Requires jQuery
** Include this file or copy/paste into your document.
** Call the function, passing the selector as a jQuery-style string.
** Offset is a number used to keep the text just short of the width of the parent to avoid rounding errors that will wrap the text.
** You can use the offset to adjust how close you want the width to be. Offset is optional and defaults to 10.
** Step defines the increase in font size. If you find one or more of your elements pushes out further than the others, adjust this
** number.
** For this to work, the element containing the text must be set to display:inline or inline-block, and the parent should be anything
** other than inline. So, if you have an h1 inside a header, you will need to make sure the h1 is inline or inline-block and the header
** isn't inline.
*/
function pmft(selector, offset, step){
if(offset == null){
offset = 10;
}
if(step == null){
step = 1;
}
var containerWidth = $(selector).parent().outerWidth(true),
thisWidth = $(selector).outerWidth(true) + offset,
thisFontSize = parseFloat($(selector).css('font-size'));
if($(selector).length && thisWidth != NaN && containerWidth != NaN){
if(thisWidth < containerWidth){
while(thisWidth < containerWidth){
thisFontSize += step;
$(selector).css('font-size', thisFontSize + 'px');
thisWidth = $(selector).outerWidth(true) + offset;
}
} else if (thisWidth > containerWidth){
while(thisWidth > containerWidth){
thisFontSize -= step;
$(selector).css('font-size', thisFontSize + 'px');
thisWidth = $(selector).outerWidth(true) + offset;
}
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment