Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3615446
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T22:22:28+00:00 2026-05-18T22:22:28+00:00

i’m trying to get back a style property in all valid ‘length’ and ‘percent’

  • 0

i’m trying to get back a style property in all valid ‘length’ and ‘percent’ units, converted from the original value set for that property.

e.g., if i have a div with style.width set to 20%, i’d want back an object with that value in percent (of course, 20%), pixels (whatever the actual pixel width is), em, pt, ex, etc.

i realize that ‘percentage’ is not a ‘length’ value, and that not all properties that accept length values accept percentage, but want to include that as well.

of course, some values will be dependent on the element specifically, and possibly it’s position in the DOM (e.g., getting the em value will require that element’s parent computed font size as well).

i can assume that the style is set explicitly for the element – i’m aware of how to retrieve the current computed style of an element – i’m just hoping to not repeat work someone else has probably already done. i’m also aware of http://www.galasoft.ch/myjavascript/WebControls/css-length.html, but it relies on style.pixelWidth or node.clientWidth, and fails in Chrome (I’d assume it fails in Safari as well… and probably others).

i’ve already got color values worked out (rgb, rgba, hex, name) – this is of course a lot more straightforward. i’m working with values that are mathematically mutable, so really only need ‘length’ and ‘percent’ values (if called on a property set with a non-length, non-percent value – like ‘font-size: larger’ – the function could fail, or throw an error).

if written procedurally, something like this would be ideal:

function getUnits(target, prop){
  var value = // get target's computed style property value
  // figure out what unit is being used natively, and it's values - for this e.g., 100px
  var units = {};
  units.pixel = 100;
  units.percent = 50;  // e.g., if the prop was height and the parent was 200px tall
  units.inch = 1.39;  // presumably units.pixel / 72 would work, but i'm not positive
  units.point = units.inch / 72;
  units.pica = units.point * 12;
  // etc...
  return units;
}

I’m not asking for someone to write code for me, but my hope is that someone has already done this before and it’s available in some open-source library, framework, blog post, tut, whatever. failing that, if someone has a clever idea how to streamline the process, that’d be great as well (the author of the link above created a temporary div and computed a single value to determine the ratios for other units – a handy idea but not one i’m entirely sold on, and definitely one that’d need supplemental logic to handle everything i’m hoping accept).

thanks in advance for any insight or suggestions.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T22:22:28+00:00Added an answer on May 18, 2026 at 10:22 pm

    EDIT: updated to allow user to pick a single unit to be returned (e.g., exists as %, get back in px) – big improvement in performance for when that’s enough – might end up changing it to just accept a single unit to convert, and get rid the loops. Thanks to eyelidlessness for his help. /EDIT

    this is what i’ve come up with – after preliminary testing it appears to work. i borrowed the temporary div idea from the link mentioned in the original question, but that’s about all that was taken from that other class.

    if anyone has any input or improvements, i’d be happy to hear it.

       (function(){
    
        // pass to string.replace for camel to hyphen
        var hyphenate = function(a, b, c){
            return b + "-" + c.toLowerCase();
        }
    
        // get computed style property
        var getStyle = function(target, prop){
            if(prop in target.style){  // if it's explicitly assigned, just grab that
                if(!!(target.style[prop]) || target.style[prop] === 0){
                    return target.style[prop];
                }
            }
            if(window.getComputedStyle){ // gecko and webkit
                prop = prop.replace(/([a-z])([A-Z])/, hyphenate);  // requires hyphenated, not camel
                return window.getComputedStyle(target, null).getPropertyValue(prop);
            }
            if(target.currentStyle){ // ie
                return target.currentStyle[prop];
            }
            return null;
        }
    
        // get object with units
        var getUnits = function(target, prop, returnUnit){
    
            var baseline = 100;  // any number serves 
            var item;  // generic iterator
    
            var map = {  // list of all units and their identifying string
                pixel : "px",
                percent : "%",
                inch : "in",
                cm : "cm",
                mm : "mm",
                point : "pt",
                pica : "pc",
                em : "em",
                ex : "ex"
            };
    
            var factors = {};  // holds ratios
            var units = {};  // holds calculated values
    
            var value = getStyle(target, prop);  // get the computed style value
    
            var numeric = value.match(/\d+/);  // get the numeric component
            if(numeric === null) {  // if match returns null, throw error...  use === so 0 values are accepted
                throw "Invalid property value returned";
            }
            numeric = numeric[0];  // get the string
    
            var unit = value.match(/\D+$/);  // get the existing unit
            unit = (unit == null) ? "px" : unit[0]; // if its not set, assume px - otherwise grab string
    
            var activeMap;  // a reference to the map key for the existing unit
            for(item in map){
                if(map[item] == unit){
                    activeMap = item;
                    break;
                }
            }
            if(!activeMap) { // if existing unit isn't in the map, throw an error
                throw "Unit not found in map";
            }
    
            var singleUnit = false;  // return object (all units) or string (one unit)?
            if(returnUnit && (typeof returnUnit == "string")) {  // if user wants only one unit returned, delete other maps
                for(item in map){
                    if(map[item] == returnUnit){
                        singleUnit = item;
                        continue;
                    }
                    delete map[item];
                }
            }
    
            var temp = document.createElement("div");  // create temporary element
            temp.style.overflow = "hidden";  // in case baseline is set too low
            temp.style.visibility = "hidden";  // no need to show it
    
            target.parentNode.appendChild(temp);    // insert it into the parent for em and ex  
    
            for(item in map){  // set the style for each unit, then calculate it's relative value against the baseline
                temp.style.width = baseline + map[item];
                factors[item] = baseline / temp.offsetWidth;
            }
    
            for(item in map){  // use the ratios figured in the above loop to determine converted values
                units[item] = (numeric * (factors[item] * factors[activeMap])) + map[item];
            }
    
            target.parentNode.removeChild(temp);  // clean up
    
            if(singleUnit !== false){  // if they just want one unit back
                return units[singleUnit];
            }
    
            return units;  // returns the object with converted unit values...
    
        }
    
        // expose           
        window.getUnits = this.getUnits = getUnits;
    
    })();
    

    tyia

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have a text area in my form which accepts all possible characters from
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
Let's say I'm outputting a post title and in our database, it's Hello Y’all
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am currently running into a problem where an element is coming back from
Basically, what I'm trying to create is a page of div tags, each has
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.