Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Dynamic Web Font Sizes
<!DOCTYPE html>
<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="generator" content="TextMate">
<meta name="author" content="Brian Pfeil">
<link rel="stylesheet" href="" type="text/css" media="screen" title="no title" charset="utf-8">
<script src="" type="text/javascript" charset="utf-8"></script>
<script src="" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
function l(s) {
var log = document.getElementById('log');
var e = document.createElement('div');
e.appendChild( document.createTextNode(s) );
jQuery(function($) {
function bestFitTextSize(text, css, width, height) {
var pixel = 1;
do {
css['font-size'] = (pixel++) + 'px';
s = sizeWithText(text, css);
} while ( (s.w < width) && (s.h < height) )
return pixel - 2;
function sizeWithText(text, cssStyles) {
// create temp element to hold our text
var e = document.createElement('span');
// apply any styles that have been passed in
// to our element - these can affect the text size
for (var prop in cssStyles) {[prop] = cssStyles[prop];
// hide our temp element['visibility'] = 'hidden';
// add to DOM in order to have it render
// get the bounding rectangle dimensions
var s = {w: e.offsetWidth, h: e.offsetHeight};
// remove from DOM
return s;
// box we want to fill with text
var c = document.getElementById('content');
// out text
var text = 'Lorem ipsum dolor sit amet';
// styles
var cssStyles = {
'font-family': 'Impact',
'font-style': 'normal',
'font-weight': 'bolder',
'letter-spacing': '1px',
'text-shadow': '3px 3px 3px white'
// size the text to fit
function applyBestFitText() {
// get the pixel size for the font
var px = bestFitTextSize(text, cssStyles, c.offsetWidth, c.offsetHeight);
cssStyles['font-size'] = px + 'px';
// set the text
c.innerHTML = text;
// apply our styles
for (var prop in cssStyles) {[prop] = cssStyles[prop];
// adjust if the size changes
window.addEventListener('resize', applyBestFitText, false);
// call for first time adjustment
<style type="text/css" media="screen">
#content {
min-width: 200px;
max-width: 800px;
height: 100px;
background-color: rgba(0,0,0,0.3);
<div id='content'></div>
<div id='log'></div>
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.