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:

1
//this function returns the computed pixel value
2
//of 1em relative to the given element
3
function getComputedEm(el) {
4
var tdiv = document.createElement('div')
5
tdiv.style.height = '1em'
6
tdiv.style.position = 'absolute'
7
tdiv.style.backgroundColor = '#f00'
8
el.appendChild(tdiv)
9
var emValue = tdiv.offsetHeight
10
el.removeChild(tdiv)
11
return emValue
12
}
13
//this function takes an integer, and a javascript element.
14
function convertPixelsToEms(pixels, el) {
15
var emval = getComputedEm(el)
16
var value = pixels / emval
17
return Math.round(value * 100) / 100
18
}

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.