Skip to content

Instantly share code, notes, and snippets.

@charliepark
Last active August 29, 2015 14:02
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 charliepark/d66b241cf407f542360f to your computer and use it in GitHub Desktop.
Save charliepark/d66b241cf407f542360f to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div{background:#eee;margin:10px;width:350px;border:20px solid #ccc;padding:10px}
p{font-family:courier;margin:0;padding:0;}
</style>
</head>
<body>
<div style="height:180px;"><p class="js-fit">This is some text to resize.</p></div>
<div style="height:60px;"><p class="js-fit">You can see <a href="http://codepen.io/charliepark/pen/FqdCv">a working demo</a> at CodePen.</div>
<script type="text/javascript">
// Fit is a very simple means of incrementing the height of a font until it fits within the vertical space allotted for it.
// It requires the text elements to have a class of 'js-fit'.
// It's similar in general concept to other dynamic font resizers, but it has no dependencies.
//
// Run it by calling Fit.run();
Fit = {};
Fit.adjustCurrentFontSize = function(el, amount){
var fontSize = el.style.fontSize;
if(fontSize === ''){fontSize = "16px";}
el.style.fontSize = parseInt(fontSize, 10) + amount + "px";
};
Fit.run = function(){
var items = document.getElementsByClassName('js-fit');
var itemsLength = items.length;
for(var i=0; i < itemsLength; i++){
var el = items[i];
var parentHeight = parseInt(getComputedStyle(el.parentNode).height, 10);
while(el.offsetHeight < parentHeight){ Fit.adjustCurrentFontSize(el, 1); }
while(el.offsetHeight > parentHeight){ Fit.adjustCurrentFontSize(el, -1); }
}
}
// that's all you need for Fit! Easy!
// from here down is some code to run the function on page loads and resizes.
ready = function(fn) {
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState === 'interactive')
fn();
});
}
};
addEvent = function(elem, type, eventHandle) {
if (elem == null || typeof(elem) == 'undefined') return;
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( 'on' + type, eventHandle );
} else {
elem['on'+type]=eventHandle;
}
};
ready(Fit.run);
addEvent(window, 'resize', Fit.run);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment