Thoughts

Convert Pixels To Ems - A Bookmarklet

Recently, I was writing a Javascript app that involved some animated, expanding boxes. While doing this, I realized I needed a way to dynamically convert pixels to computed ems. The function wasn't too complicated, and so I decided to make a bookmarklet out of it that did the same thing. It was kind of fun. Hopefully you'll find it useful, either in javascript, or to remove the headache when you're trying to create pixel-perfect designs using ems

The Function

So, here are the functions:


//this function returns the computed pixel value 
//of 1em relative to the given element
function getComputedEm(el){
	var tdiv = document.createElement("div");
	tdiv.style.height = "1em";
	tdiv.style.position = "absolute";
	tdiv.style.backgroundColor = "#f00";
	el.appendChild(tdiv);
	var emValue = tdiv.offsetHeight;
	el.removeChild(tdiv);
	return emValue;
} 
//this function takes an integer, and a javascript element.
function convertPixelsToEms(pixels, el){
	var emval = getComputedEm(el);
	var value = pixels/emval;
	return Math.round(value*100)/100;
}

The Bookmarklet

And here's the bookmarklet:

pixel2em

Just drag the link above to your menu bar, and click on it in any site. The bookmarklet will appear at the top of the page. It takes a pixel amount, and any css selector you can think of, so it will return the conversion relative to an element. For example, on this site, if you use "body", 16 pixels = 1.14em, but if you use #content p, 16 pixels = 1.23em.

It's probably not perfect, so please let me know if things aren't working correctly. Although, I can tell you right now it's not going to work on ie6, so don't bother trying it there.

The bookmarklet makes use of Dean Edward's cssQuery, a slick little script to retrieve elements based on CSS selectors.

All in all, this was a fun experiment, and I hope you find it useful. Have fun.