Reputation: 801
I have a website that is heavily based on jQuery; meaning much of it's content is created, measured, & set by jQuery.
All these measurements are px. I need to either convert them to em or, preferably, create a function that will convert them for me. This would be easy if all the font-size was 16px (or 100%); this is not the case, however. I need it to detect the font-size of the container & go from there.
Upvotes: 0
Views: 1101
Reputation: 801
I figured it out. You can see the code here.
function px_to_em(px_value, container) {
////////////////////////////////
// Detect Contianer Font Size //
////////////////////////////////
//Prepend a span tag to the container for testing
$(container).prepend("<span id='wraping_span_to_test'></span>");
//Set the span to height 1em and then save the pixel height to the container_ft_sz variable
container_ft_size = $("#wraping_span_to_test").css({
"font-family": "inherit",
"font-size": "inherit",
"font-style": "inherit",
"font-variant": "inherit",
"font-weight": "inherit",
"line-height": "inherit",
"margin": "0 !important",
"padding": "0 !important",
"border": "0 !important",
"outline": "0 !important",
"background-color": "aqua",
"height": "1em",
"width": " 1em",
"display": "block"
}).height();
//Remove the testing span
$("#wraping_span_to_test").remove();
//Use values to convert to ems
var round_to = 1000;
return Math.round((px_value / container_ft_size) * round_to) / round_to;
}
This should allow you to find measurements with jQuery that is measured by pixels & convert them into em measurements by calling a simple function.
Upvotes: 1
Reputation: 465
This isn't easy. Thinking about it you could temporarily insert content with width:1em, measure the width in px, and calculate the em you need from there.
Upvotes: 0