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 value2//of 1em relative to the given element3function getComputedEm(el) {4var tdiv = document.createElement('div')5tdiv.style.height = '1em'6tdiv.style.position = 'absolute'7tdiv.style.backgroundColor = '#f00'8el.appendChild(tdiv)9var emValue = tdiv.offsetHeight10el.removeChild(tdiv)11return emValue12}13//this function takes an integer, and a javascript element.14function convertPixelsToEms(pixels, el) {15var emval = getComputedEm(el)16var value = pixels / emval17return Math.round(value * 100) / 10018}
The Bookmarklet
And here's the bookmarklet:
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.