Skip to content

Instantly share code, notes, and snippets.

@eykd
Forked from blaine/gist:428898
Created September 27, 2010 20:54
Show Gist options
  • Save eykd/599812 to your computer and use it in GitHub Desktop.
Save eykd/599812 to your computer and use it in GitHub Desktop.
Sets the size of the body text to whatever works best for the current device. Based on code from http://blog.romeda.org/2010/06/beautiful-lines.html
var setTextMeasure = function (contentElement, targetMeasure, maxSize, minSize) {
if (!contentElement) contentElement = document.createElement('p');
if (!targetMeasure) targetMeasure = 66;
if (!maxSize) maxSize = 16;
if (!minSize) minSize = 9;
var sizer = contentElement.cloneNode();
sizer.style.cssText = 'margin: 0; padding: 0; color: transparent; background-color: transparent; position: absolute;';
var letters = 'aaaaaaaabbcccddddeeeeeeeeeeeeeffgghhhhhhiiiiiiijkllllmmnnnnnnnooooooooppqrrrrrrsssssstttttttttuuuvwxyyz';
sizer.textContent = letters;
document.body.appendChild(sizer);
var characterWidth = sizer.offsetWidth / letters.length;
document.body.removeChild(sizer);
var contentWidth = contentElement.offsetWidth;
var measuredFontSize = parseFloat(
document.defaultView.
getComputedStyle(document.body, null).
getPropertyValue('font-size').
replace('px', '') );
var actualMeasure = contentWidth / characterWidth;
var newMeasure = measuredFontSize * actualMeasure / targetMeasure;
if (newMeasure > maxSize) newMeasure = maxSize;
if (newMeasure < minSize) newMeasure = minSize;
document.body.style.fontSize = newMeasure + "px";
}
@eykd
Copy link
Author

eykd commented Sep 27, 2010

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