Dealing with CSS unit conversions in jQuery (px to em to percentages)
I spent some time working on a plugin to convert px to em and percentages for the upcoming Wordspot site.
The problem lies in the fact that measurements are based on the element they are attached to. Thus, to convert any CSS property (i.e. “5em” or “20%”) to pixels, one must determine what the relative height of a single line of text is in pixels.
This tool creates an invisible child element, measures a single line of text, and uses that for measurements.
Thus, to convert 90% (or any measurement, for that matter) to pixels, you could do the following:
var borderRadiusPixels = $.UnitConverter.px( $('#mydiv').css('border-top-left-radius') ); |
For more advanced operations, you can do things like this:
// create a new unit conversion var measurement = new $.UnitConverter( $('#mydiv') ); // load a value to be examined measurement.load( $('#mydiv').css('border-left-width') ); // add 10% to the height measurement.add( '10%' ); // convert the measurement to various output types var pxs = measurement.px(); var ems = measurement.convert( 'em' ); var pct = measurement.convert( '%' ); // determine what the measurement would be in another element (i.e. with a different line height) var clonePxs = measurement.clone( $('#nudderElement') ).px(); |
Hopefully this will give you a good head start on conquering similar issues, without having to invent any wheels!
Comments off