Skip to content

Instantly share code, notes, and snippets.

@ronaldroe ronaldroe/pmft.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.