Forum Moderators: open

Message Too Old, No Replies

EM size solved

How to detect EM size

         

Dabrowski

5:21 pm on Apr 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I know this is a topic that has come up before, and something I ran into. Couldn't find a solution anyway so I came up with one, and here it is.

var emSizeDiv;

function installEMsize() {
var body = document.body;
var div = document.createElement( "DIV");

div.style.position = "absolute";
div.style.top = "10px";
div.style.right = "10px";
div.style.display = "none";

div.style.margin = 0;
div.style.padding = 0;
div.style.borderWidth = 0;

div.style.lineHeight = "1em";

div.setAttribute( "id", "emsizedetect");
div.appendChild( document.createTextNode( "M"));

body.appendChild( div);

emSizeDiv = document.getElementById( "emsizedetect");
}

function getEMsize() {
var emSize;

if(!emSizeDiv) installEMsize();

emSizeDiv.style.display = "block";
emSize = emSizeDiv.offsetHeight;
emSizeDiv.style.display = "none";

return emSize;
}

This will detect the document's default font-size in pixels. No matter if it's not defined, or defined in something other than pixels, pt or % for example.

It works in IE6, IE7 and FF.

It's also sensitive to browser font size changes, I know in IE at least this doesn't change the font size applied to <body>.

Just call getEMsize() as many times as you like. No need to run the install function yourself, it'll do this automatically.

Dabrowski

5:23 pm on Apr 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As a side note, this version return the pixel value, I have found it easier to make emSize a global so it's there when you need it. Multiple calls to find the div, show it and hide it seem a waste of CPU time.