I\'m having a hard time getting my head around font scaling.
I currently have a website with a body font-size
of 100%. 100% of what though? This seems t
This worked for me:
I try to approximate font-size based on a width/height got from setting `font-size: 10px`. Basically, the idea is "if I have 20 pixels width and 11 pixels height with `font-size: 10px`, so what would it be the maximum font-size to math a container of 50 pixels width and 30 pixels height?"
The answer is a double proportion system:
{ 20:10=50:X, 11:10=30:Y } = { X= (10*50)/20, Y= (10*30)/11 }
Now X is a font-size that will match width, and Y is a font-size that will match height; take the smallest value
function getMaxFontSizeApprox(el){
var fontSize = 10;
var p = el.parentNode;
var parent_h = p.offsetHeight ? p.offsetHeight : p.style.pixelHeight;
if(!parent_h)
parent_h = 0;
var parent_w = p.offsetHeight ? p.offsetWidth : p.style.pixelWidth;
if(!parent_w)
parent_w = 0;
el.style.fontSize = fontSize + "px";
var el_h = el.offsetHeight ? el.offsetHeight : el.style.pixelHeight;
if(!el_h)
el_h = 0;
var el_w = el.offsetHeight ? el.offsetWidth : el.style.pixelWidth;
if(!el_w)
el_w = 0;
// 0.5 is the error on the measure that JavaScript does
// if the real measure had been 12.49 px => JavaScript would have said 12px
// so we think about the worst case when could have, we add 0.5 to
// compensate the round error
var fs1 = (fontSize*(parent_w + 0.5))/(el_w + 0.5);
var fs2 = (fontSize*(parent_h) + 0.5)/(el_h + 0.5);
fontSize = Math.floor(Math.min(fs1,fs2));
el.style.fontSize = fontSize + "px";
return fontSize;
}
NB: the argument of the function must be a span element or an element which is smaller than its parent, otherwise if children and parent have both the same width/height function will fail.